LeetCode解题之Remove Duplicates from Sorted List


原题

删除一个有序链表中反复的元素,使得每一个元素仅仅出现一次。

注意点:

样例:

输入: 1->1->2->3->3

输出: 1->2->3

解题思路

顺序遍历全部节点,假设当前节点有后一个节点,且它们的值相等,那么当前节点指向后一个节点的下一个节点,这样就能够去掉反复的节点。

AC源代码

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

    def my_print(self):
        print(self.val)
        if self.next:
            print(self.next.val)


class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        curr = head
        while curr:
            while curr.next and curr.val == curr.next.val:
                curr.next = curr.next.next
            curr = curr.next
        return head


if __name__ == "__main__":
    n1 = ListNode(1)
    n2 = ListNode(1)
    n3 = ListNode(2)
    n1.next = n2
    n2.next = n3
    r = Solution().deleteDuplicates(n1)
    r.my_print()

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

posted on 2017-06-26 11:02  yutingliuyl  阅读(116)  评论(0编辑  收藏  举报