# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution1:
"""
slow&fater pointer
remember to make slow.next equal to None after jump out of the loop
"""
def deleteDuplicates(self, head) :
if head == None: return head
slow, fast = head, head
while(fast):
if fast.val == slow.val:
fast = fast.next
else:
slow.next = fast
fast = fast.next
slow = slow.next
slow.next = None
return head
class Solution2:
"""
recursion way use last_val to record last distinct node's val
faster than 99.98%
"""
def deleteDuplicates(self, head):
return self.helper(head, float("inf"))
def helper(self, head, last_val):
if head is None: return head
if head.val == last_val:
return self.helper(head.next, last_val)
else:
head.next = self.helper(head.next, head.val)
return head
class Solution3:
"""
use one variable , delete next node if next node's val is the same
"""
def deleteDuplicates(self, head):
pNode = head
while(pNode):
while(pNode.next and pNode.val == pNode.next.val):
pNode.next = pNode.next.next
pNode = pNode.next
return head
class Solution4:
"""
use one loop, what is different from solution3 is that, s3 use one loop to get next node
but s4 use loop again and again to find next node
"""
def deleteDuplicates(self, head):
if head is None: return head
pNode = head
while(pNode.next):
if pNode.val == pNode.next.val:
pNode.next = pNode.next.next
else:
pNode = pNode.next
return head
【Leetcode】83. Remove Duplicates from Sorted List
最新推荐文章于 2024-11-10 15:36:20 发布