给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数 ,链表中每个节点的值满足
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 the head # @return bool布尔型 # class Solution: def isPail(self , head ): # write code here # 节点值比较方法 # if not head: # return True # stack = [] # cur = head # while cur: # stack.append(cur.val) # cur = cur.next # return stack == stack[::-1] # 快慢指针找中点 if not head&nbs***bsp;not head.next: return True slow = head fast = head while fast and fast.next: pre = slow slow = slow.next fast = fast.next.next # 从中点断开 分成两条链 head and slow pre.next = None # 链表反转 head2 = None while slow: temp = slow.next slow.next = head2 head2 = slow slow = temp while head and head2: if head.val != head2.val: return False head = head.next head2 = head2.next return True
#时间未通过 class Solution: def isPail(self , head ): # write code here rev=self.Reverse(head) result=self.isSame(head, rev) return result def Reverse(self, head): temp=newhead=head curr=None while temp: newhead=ListNode(temp.val) newhead.next=curr curr=newhead temp=temp.next return newhead def isSame(self, head1, head2): while head1 and head2: if head1.val != head2.val: return False head1=head1.next head2=head2.next return True
为啥会超时呢。。。 class Solution: def isPail(self , head ): # write code here if not head&nbs***bsp;not head.next: return True left, right = self.cut(head) right = self.reverse(right) while left and right: if left.val != right.val: return False left = left.next right = right.next return True def cut(self, head): slow = fast = head i = 0 while fast and fast.next: fast = fast.next.next slow = slow.next i += 1 if i % 2 == 1: cut = slow else: cut = slow.next slow = None return head, cut def reverse(self, head): if not head&nbs***bsp;not head.next: return head tail = None while head: tmp = head.next head.next = tail tail = head head = tmp return tail