力扣题目链接:https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/
给定一个已排序的链表的头?head
,?删除原始链表中所有重复数字的节点,只留下不同的数字?。返回 已排序的链表?。
?
示例 1:
输入:head = [1,2,3,3,4,4,5] 输出:[1,2,5]
示例 2:
输入:head = [1,1,1,2,3] 输出:[2,3]
?
提示:
[0, 300]
内-100 <= Node.val <= 100
相同的节点可能被全部删除(头节点可能也会被删),因此我们可以新建一个“空的头节点ans”,ans的next指向head。
使用两个节点lastNode和thisNode,lastNode指向上一个节点(防止当前遍历到的节点被删除),thisNode指向当前处理到的节点。当thisNode和thisNode.next都非空时:
thisNode.val == thisNode.next.val
,新建一个nextNode节点指向thisNode.next.next(最终指向第一个和thisNode的值不同的节点)。当nextNode非空且nextNode.val == thisNode.val
时,nextNode不断后移。最后将lastNode.next赋值为nextNode,并将thisNode赋值为nextNode(删掉了中间具有相同元素的节点)。最终返回“假头节点”ans的next即可。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* ans = new ListNode(1000, head);
ListNode* lastNode = ans, *thisNode = head;
while (thisNode && thisNode->next) {
if (thisNode->val == thisNode->next->val) {
ListNode* nextNode = thisNode->next->next;
while (nextNode && thisNode->val == nextNode->val) {
nextNode = nextNode->next;
}
lastNode->next = nextNode;
thisNode = nextNode;
}
else {
lastNode = thisNode, thisNode = thisNode->next;
}
}
return ans->next;
}
};
# from typing import Optional
# # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
ans = ListNode(1000, head)
lastNode, thisNode = ans, head
while thisNode and thisNode.next:
if thisNode.val == thisNode.next.val:
nextNode = thisNode.next.next
while nextNode and thisNode.val == nextNode.val:
nextNode = nextNode.next
lastNode.next = nextNode
thisNode = nextNode
else:
lastNode, thisNode = thisNode, thisNode.next
return ans.next
同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/135612345