title :
Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from the Original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
code : OJ online test via 288 ms
1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8 #@param head, a listnode9 #@return a ListNodeTen defdeleteduplicates (Self, head): One ifHead isNoneorHead.next isNone: A returnHead - -Dummyhead =listnode (0) theDummyhead.next =Head - -p =Dummyhead - whileP.next is notNone andP.next.next is notNone: +TMP =P - whileTmp.next.val = =Tmp.next.next.val: +TMP =Tmp.next A ifTmp.next.next isNone: at Break - ifTMP = =P: -p =P.next - Else: - ifTmp.next.next is notNone: -P.next =Tmp.next.next in Else: -P.next =Tmp.next.next to Break + returnDummyhead.next
Ideas :
Set up the virtual table header Hummyhead to handle the linked list in a convenient way
P.next always points to the element to compare
A while loop is then nested in a while loop, skipping over the repeating elements.
If a repeating element is encountered: P does not move, p.next changes; If duplicate elements are not encountered, P=p.next
Tips: It is best to add a logical judgment pointer before using the pointer is not empty
Leetcode "Remove duplicates from Sorted List II" Python implementation