</>复制代码
Given a sorted linked list, delete all nodes that have duplicate
numbers, leaving only distinct numbers from the original list.
https://leetcode.com/problems...
</>复制代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
# Two nodes: one to keep head, one to keep tail.
ahead = phead = ListNode("null")
# Two pointers: one to move ahead, one to monitor duplicates.
p = None
c = head
# When move to end, terminate.
while c:
# At the beginning, simple move one step forward.
if p == None:
p = c
# If p and c have different values, need to determine why.
elif p.val != c.val:
# If p and c are neighbors, p must be unique value.
if p.next == c:
phead.next = p
phead = phead.next
phead.next = None
# p gets one step forward.
p = c
# If p and c are not neighbors, ignore nodes with p.val.
else:
p = c
# c moves one step anyway.
c = c.next
# If p is not None (input not empty) and has next, collect last element.
if p != None and p.next == None:
phead.next = p
return ahead.next
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/43626.html
摘要:题目要求翻译将链表中重复的元素全部删除,返回新的头结点。相比于,这里将重复的元素全部删除。除此以外,我们还需要知道重复元素的前一个值和重复元素的最后一个值。如果存在重复值,则跳过重复值后,前节点不变,否则前节点跟随后节点同时向后移动。 题目要求 Given a sorted linked list, delete all nodes that have duplicate number...
摘要:和上一道题不同的地方就是,需要用双指针操作,且最后要返回,以防止结点即的情况返回错误的结果。令,用进行查重操作,是的前结点。当和等值的时候,后移至第一个不等值的点,用指向新的即可。 Remove Duplicates form Sorted List I Problem Given a sorted linked list, delete all duplicates such tha...
摘要:思路与代码其实在这里我们仍然延续中的思路。在遇到非重复值以及非多余的重复值时,将数值移动到当前记录的下标上。保证该下标前的值均为满足题目条件的值。第一次我使用了来记录某个值出现的次数。 题目要求 Follow up for Remove Duplicates: What if duplicates are allowed at most twice? For example, Giv...
摘要:自己没事刷的一些的题目,若有更好的解法,希望能够一起探讨项目地址 自己没事刷的一些LeetCode的题目,若有更好的解法,希望能够一起探讨 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...
摘要:微信公众号记录截图记录截图目前关于这块算法与数据结构的安排前。已攻略返回目录目前已攻略篇文章。会根据题解以及留言内容,进行补充,并添加上提供题解的小伙伴的昵称和地址。本许可协议授权之外的使用权限可以从处获得。 Create by jsliang on 2019-07-15 11:54:45 Recently revised in 2019-07-15 15:25:25 一 目录 不...
阅读 3357·2021-11-11 11:00
阅读 2682·2019-08-29 11:23
阅读 1554·2019-08-29 10:58
阅读 2461·2019-08-29 10:58
阅读 3055·2019-08-23 18:26
阅读 2582·2019-08-23 18:18
阅读 2112·2019-08-23 16:53
阅读 3486·2019-08-23 13:13