原题链接:https://leetcode.com/problems/palindrome-linked-list/
我自己的想法是把这个链表复制一份然后倒过来,对比一下两个链表是否一样。想法简单但是操作起来非常复杂···链表的复制和比较都用自定义func来实现的。
顺便总结一下copy.copy和copy.deepcopy的区别
a = [1,2,3]
b = copy.copy(a)
c = copy.deepcopy(a)
在上面两个复制的值b和c中,b里储存的实际上是指向a的地址,一旦a改变b也会随之改变;而c储存的是a的复制值,不会随着a的改变而改变。
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
return self.compare(self.dpy_ll(head), self.reverse(head))
def compare(self, a, b):
while a and b:
if a.val == b.val:
a,b = a.next, b.next
else:
return False
#handle a b have different length
if b == None and a != None:
return False
elif b != None and a == None:
return False
else:
return True
def dpy_ll(self, head):
dummy = ListNode(-1)
curr = head
prev = dummy
while curr:
curr_dpc = copy.copy(curr)
prev.next = curr_dpc
curr = curr.next
prev = curr_dpc
return dummy.next
def reverse(self, head):
prev = None
curr = head
while curr:
next_ = curr.next
curr.next = prev
prev = curr
curr = next_
return prev
看了讨论里别人写的答案,太厉害了,其实问题的关键在于值是否相等,所以直接将链表上的值复制下来然后倒过来对比就好,简单了很多速度也更快。
class Solution:
def isPalindrome(self, head):
list_s=[]
while head:
list_s.append(head.val)
head=head.next
return list_s==list_s[::-1]
网友评论