zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):082

    题目来源


    https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.


    题意分析


    Input:

    :type head: ListNode

    Output:

    :rtype: ListNode

    Conditions:与83题不同,只要元素出现过,则将该元素去掉


    题目思路


    因为list是有序的,并且可能返回一个空list,所以增加一个头节点。再增加一个节点时,就看这个节点之后是否有值与这个节点的值重复,如果有就不加这个值的【所有】节点


    AC代码(Python)

     1 # Definition for singly-linked list.
     2 # class ListNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution(object):
     8     def deleteDuplicates(self, head):
     9         """
    10         :type head: ListNode
    11         :rtype: ListNode
    12         """
    13         if head == None or head.next == None:
    14             return head
    15         
    16         ans = ListNode(-1)
    17         ans.next = head
    18         p = ans
    19         temp = p.next
    20         
    21         while p.next:
    22             while temp.next and temp.next.val == p.next.val:
    23                 temp = temp.next
    24             if p.next == temp:
    25                 p = p.next
    26                 temp = p.next
    27             else:
    28                 p.next = temp.next
    29         
    30         return ans.next
    31             
    32         
  • 相关阅读:
    [极客大挑战 2019]BuyFlag
    [极客大挑战 2019]BabySQL
    [网鼎杯 2018]Fakebook
    C语言学习笔记_内存数据和字符串
    剑指OFFER_数据流中的中位数
    剑指OFFER_滑动窗口的最大值
    剑指OFFER_矩阵中的路径
    C语言学习笔记_指针相关知识
    剑指OFFER_机器人的运动范围
    剑指OFFER_剪绳子
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5367025.html
Copyright © 2011-2022 走看看