title :
Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Code :
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.next - - whileP.next is notNone: + ifP.val = =P.next.val: -P.next =P.next.next + Else: Ap =P.next at - returnDummyhead.next
Ideas :
Set up virtual table header Dummyhead
Meet Val different, then execute p=p.next; otherwise the pointer p does not move, only the p.next changes.
Leetcode "Remove duplicates from Sorted List" Python implementation