zoukankan      html  css  js  c++  java
  • leetcode 【 Remove Duplicates from Sorted List II 】 python 实现

    题目

    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.

    代码:oj在线测试通过 288 ms

     1 # Definition for singly-linked list.
     2 # class ListNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution:
     8     # @param head, a ListNode
     9     # @return a ListNode
    10     def deleteDuplicates(self, head):
    11         if head is None or head.next is None:
    12             return head
    13         
    14         dummyhead = ListNode(0)
    15         dummyhead.next = head
    16         
    17         p = dummyhead
    18         while p.next is not None and p.next.next is not None:
    19             tmp = p
    20             while tmp.next.val == tmp.next.next.val:
    21                 tmp = tmp.next
    22                 if tmp.next.next is None:
    23                     break
    24             if tmp == p:
    25                 p = p.next
    26             else:
    27                 if tmp.next.next is not None:
    28                     p.next = tmp.next.next
    29                 else:
    30                     p.next = tmp.next.next
    31                     break
    32         return dummyhead.next

    思路

    设立虚表头 hummyhead 这样处理Linked List方便一些

    p.next始终指向待比较的元素

    while循环中再嵌套一个while循环,把重复元素都跳过去。

    如果遇到了重复元素:p不动,p.next变化;如果没有遇到重复元素,则p=p.next

    Tips: 使用指针之前 最好加一个逻辑判断 指针不为空

  • 相关阅读:
    大道至简第一张读后感
    字符串加密
    写一个类,在任何时候都可以向它查询创建了多少个类
    类与对象动手动脑
    2016年读书清单
    2016-09-01
    Spring笔记(五)--注解方式实现AOP
    Spring笔记(三)--代理模式
    Spring笔记(四)--公共属性的配置
    表达式之谜
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4186852.html
Copyright © 2011-2022 走看看