美文网首页
Q83 Remove Duplicates from Sorte

Q83 Remove Duplicates from Sorte

作者: 牛奶芝麻 | 来源:发表于2018-02-28 16:32 被阅读7次

Given 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.

解题思路:

链表删除操作的应用,即 cur.next = cur.next.next,时间复杂度为 O(n)。

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

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        if cur == None or cur.next == None:  # 如果是空链表或链表只有一个元素
            return head
        while cur.next != None:
            if cur.val == cur.next.val:  # 如果连续两个值相等,则删除后一个
                cur.next = cur.next.next
            else:  # 如果不相等,当前指针后移
                cur = cur.next
        return head

相关文章

网友评论

      本文标题:Q83 Remove Duplicates from Sorte

      本文链接:https://www.haomeiwen.com/subject/wpoctftx.html