83. &82 Remove Duplicates from Sorted List

题目要求:

Given a sorted linked list, delete all duplicates such that each element appear only once.

Examples:

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

解题思路:
  • 指针移动示意图
  • 注意else语句的链表相连操作!!!


代码:
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, repr(self.next))


    def my_print(self):
        while self:
            print(self.val)
            self = self.next


class Solution(object):
    def deleteDuplication(self, head):
        """
        :param head: ListNode
        :return: ListNode
        """
        dummy = ListNode(-1)
        dummy.next = head
        prev = dummy
        curr = head

        while curr:
            if prev.val == curr.val:
                val = curr.val
                while curr and curr.val == val:
                    curr = curr.next
                prev.next = curr
            else:
                prev.next = curr
                prev = curr
                curr = curr.next

        return dummy.next



if __name__ == "__main__":
    head, head.next, head.next.next = ListNode(1), ListNode(2), ListNode(3)
    head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(4)
    head.next.next.next.next.next, head.next.next.next.next.next.next = ListNode(4), ListNode(5)
    print(Solution().deleteDuplication(head))
补充:

while curr and curr.val == val:while curr.val == val: 相比较的话,最后curr变为None的时候没有val这个概念,所以应该先判断curr是否为None

  • 83. &82 Remove Duplicates from Sorted List_第1张图片
    没有None.val这个玩意

你可能感兴趣的:(83. &82 Remove Duplicates from Sorted List)