有一个leetcode问题83:给定排序链表的头,删除所有重复项,使每个元素只出现一次。返回已排序的链表。
例如:输入:头=[1,1,2]输出:[1,2]
我是链表的新手,我知道有更好的解决方案。Code1不起作用。当输入为[1,2,2]时,输出为[1]。Code2起作用,唯一的区别是";t.next=无";。为什么Code1不起作用?有人能解释一下吗?谢谢
编码1
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode()
t = dummy
t.val = None
while head:
if t.val != head.val:
t.next = head
t = t.next
t.next = None
head = head.next
return(dummy.next)
编码2
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode()
t = dummy
t.val = None
while head:
t.next = None
if t.val != head.val:
t.next = head
t = t.next
head = head.next
return(dummy.next)
行:
if t.val != head.val:
t.next = head
t = t.next
t.next = None
head = head.next
是问题所在。如果t.val != head.val
在某些迭代中,这些行等效于:
t.next = head
t = head
head.next = None
head = head.next # Same as head = None
这在CCD_ 2。