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: 使用指针之前 最好加一个逻辑判断 指针不为空

  • 相关阅读:
    bzoj3427:[POI2013]BAJ-Bytecomputer
    bzoj3417:[POI2013]MOR-Tales of seafaring
    bzoj1100:[POI2007]对称轴osi
    bzoj3295:[CQOI2011]动态逆序对
    bzoj2286:[SDOI2011]消耗战
    CF1110F Nearest Leaf
    CF1110E Magic Stones
    CF1110D Jongmah
    matlab基础向9:动画
    CF1102D-Balanced Ternary String-(贪心)
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4186852.html
Copyright © 2011-2022 走看看