LeetCode Remove Duplicates from Sorted List

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) 来获得相关源码。

你可能感兴趣的:(LeetCode,算法,python,链表)