• 【LeetCode每天一题】Remove Duplicates from Sorted List(移除有序链表中的重复数字)


      Given a sorted linked list, delete all duplicates such that each element appear only once.

    Example 1:

    Input: 1->1->2
    Output: 1->2
    

    Example 2:

    Input: 1->1->2->3->3
    Output: 1->2->3

    思路

      对于链表类的题目主要考的是指针的操作,他需要对指针的指向节点有正确的操作。这道题我们可以使用从头开始遍历,每当一个新节点时,都对该节点后面的节点进行比较是否相等,一直移动到和该节点不相等的节点为止,然后改变指针的指向跳过重复的元素。以直到末尾为止。这里需要主要循环结束条件等问题。时间复杂度为O(n),空间复杂度为O(1)。
    解决代码

    
    
     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 not head:    # 空节点直接返回
    14             return head
    15         pre = head     
    16         while pre:      
    17             if pre.next and pre.val == pre.next.val: # 判断当前节点的后序节点是否相等。
    18                 tem, cur = pre.val, pre.next
    19                 while cur and cur.val == tem:     # 循环移动一直到和当前节点不相等的为止。
    20                     cur = cur.next
    21                 pre.next = cur            # 指向后面一个和当前节点不相等的节点
    22                 if not cur:                 # 为空说明遍历完毕直接返回
    23                     return head
    24                 continue                
    25             pre = pre.next
    26         
    27         return head                    # 返回结果
    
    
    
    
    
  • 相关阅读:
    1
    iulg
    实验10
    作业5 指针应用
    作业4 函数应用
    实验9 指针
    实验 8 数组2
    实验7
    实验6 数组1
    实验5
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10799528.html
Copyright © 2020-2023  润新知