78 leetcode - Remove Duplicates from Sorted List

来源:互联网 发布:西北师范大学知行 编辑:程序博客网 时间:2024/06/07 10:46
#!/usr/bin/python# -*- coding: utf-8 -*-'''Remove Duplicates from Sorted ListGiven a sorted linked list, delete all duplicates such that each element appear only once.For example,Given 1->1->2, return 1->2.Given 1->1->2->3->3, return 1->2->3.'''# Definition for singly-linked list.class ListNode(object):    def __init__(self, x):        self.val = x        self.next = Noneclass Solution(object):    def deleteDuplicates(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if head == None or head.next == None:            return head        ret = head        cur = head        head = head.next        while head != None:            if head.val != cur.val:                cur.next = head                cur = cur.next            head = head.next        cur.next = None        return retif __name__ == "__main__":    s = Solution()    head = ListNode(1)    t = head    for i in [1,2,2,3,3,5,6]:        t.next = ListNode(i)        t = t.next    t.next = None    t = head    while t != None:        print t.val        t = t.next    t = s.deleteDuplicates(head)    while t != None:        print t.val        t = t.next
0 0