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

  • 没有None.val这个玩意
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容