82. Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
解题
哨兵节点的使用。加入了哨兵节点能使得头尾节点的情况和中间节点逻辑一致。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode *node = new ListNode(0);
node->next = head;
ListNode *pre = node;
while(head->next){
if(head->val != head->next->val){
if(pre->next != head){
pre->next = head->next;
head = pre->next;
}else{
pre = head;
head = head->next;
}
}else{
head = head->next;
}
}
if(pre->next != head){
pre->next = NULL;
}
return node->next;
}
};


468

被折叠的 条评论
为什么被折叠?



