Title: Remove Duplicates from Sorted List II Source: leetcode.com
Given a sorted linked list, delete all nodes that have 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
.
Python solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
''' https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ temp = head head = None last = None while temp and temp.next: flag = False while temp.next and temp.val == temp.next.val: flag = True temp1 = temp.next temp.next = temp1.next temp1.next = None temp1 = temp.next #print temp.val, temp1.val if flag: if last: last.next = temp1 temp = temp1 else: if not head: head = temp last = temp temp = temp.next if last: last.next = temp if not head: head = temp return head |