Created
March 12, 2021 06:40
-
-
Save liyunrui/2b05010e7cd004f12040bddae6b140fc to your computer and use it in GitHub Desktop.
leetcode-linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Definition for singly-linked list. | |
# class ListNode: | |
# def __init__(self, val=0, next=None): | |
# self.val = val | |
# self.next = next | |
class Solution: | |
""" | |
we need two pointers called prev and cur | |
-Initially, cur is one step forward to prev pointer. | |
-Logic | |
if prev.val == cur.val: | |
prev.next = cur.next | |
cur = cur.next | |
else: | |
prev = prev.next | |
cur = cur.next | |
d->1->1->1->2 | |
prev cur | |
return d->1->2 | |
d->1->1 | |
return d->1 | |
""" | |
def deleteDuplicates(self, head: ListNode) -> ListNode: | |
if not head: | |
return head | |
d = ListNode(None) | |
d.next = head | |
prev = d | |
cur = d.next | |
while cur: | |
if prev.val == cur.val: | |
prev.next = cur.next | |
cur = cur.next | |
else: | |
prev = prev.next | |
cur = cur.next | |
return d.next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment