'Remove Duplicates from Sorted List in Python
There's a leetcode question 83: Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
For example: Input: head = [1,1,2] Output: [1,2]
I am new to linked list and I know there're better solutions. Code1 doesn't work. When input is [1,2,2], the output is [1]. Code2 works, the only difference is the position of "t.next = None". Why doesn't Code1 work? Can someone please explain? Thanks!
Code1
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)
Code2
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)
Solution 1:[1]
The lines:
if t.val != head.val:
t.next = head
t = t.next
t.next = None
head = head.next
are the problem. If t.val != head.val in some iteration, these lines are equivalent to:
t.next = head
t = head
head.next = None
head = head.next # Same as head = None
which immediately breaks the loop the first time that t.val != head.val.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kcsquared |
