力扣题目链接:https://leetcode.cn/problems/remove-duplicates-from-sorted-list/
给定一个已排序的链表的头?head
?,?删除所有重复的元素,使每个元素只出现一次?。返回 已排序的链表?。
?
示例 1:
输入:head = [1,1,2] 输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3] 输出:[1,2,3]
?
提示:
[0, 300]
内-100 <= Node.val <= 100
当当前节点
和下一个节点
都非空时:
当前节点
和下一个节点
值相同,就删掉下一个节点
(now->next = now->next->next
)当前节点
后移(now = now->next
)最终返回传入的头节点即可。
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* ans = head;
while (head && head->next) {
if (head->val == head->next->val) {
head->next = head->next->next; // haven't delete node
}
else {
head = head->next;
}
}
return ans;
}
};
# 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 = head
while head and head.next:
if head.val == head.next.val:
head.next = head.next.next
else:
head = head.next
return ans
同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/135581000