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         
  • 相关阅读:
    什么是同源策略,什么是跨域,如何跨域,Jsonp/CORS跨域
    Scrapy
    爬虫
    Falsk-信号
    python函数中把列表(list)当参数时的"入坑"与"出坑"
    SQLAlchemy基本使用(Flask中)
    列表生成式&生成器表达式
    javascript数据结构——队列
    javascript数据结构——栈
    js数组去重的几种方法
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5367025.html
Copyright © 2011-2022 走看看