思路:将链表倒序排序之后再与原始表比较是否相等
正确的实现代码:
class Solution:
def isPail(self , head: ListNode) -> bool:
# write code here
cur = head
N0 = ListNode(-1)
while cur:
temp = N0.next
N0.next = ListNode(cur.val)
N0.next.next = temp
cur = cur.next
reversehead = N0.next
while head:
if head.val != reversehead.val:
return False
else:
head = head.next
reversehead = reversehead.next
return True
def reverseListNode(self, head: ListNode) -> ListNode:
prehead = None
while head:
temp = head.next
head.next = prehead
prehead = head
head = temp
return prehead
错误代码: 误区:不能在同一链表上做倒排操作
def isPail(self , head: ListNode) -> bool:
# write code here
cur = head
reversehead = self.reverseListNode(cur)
while head:
if head.val != reversehead.val:
return False
else:
head = head.next
reversehead = reversehead.next
return True
def reverseListNode(self, head: ListNode) -> ListNode:
prehead = None
while head:
temp = head.next
head.next = prehead
prehead = head
head = temp
return prehead