Friday, September 12, 2014

Leetcode: Remove Duplicates from Sorted List II @Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def deleteDuplicates(self, head):
        nhead=pre=ListNode(0)
        pre.next=head
        crt=head
        flag=0
        while crt and crt.next:
            if crt.next.val==crt.val:
                crt.next=crt.next.next
                flag=1
            else:
                if flag==0:
                    crt=crt.next
                    pre=pre.next
                else:
                    pre.next=crt.next
                    crt=crt.next
                    flag=0
        if flag==1:
            pre.next=crt.next
        return nhead.next

No comments :

Post a Comment