题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Return the linked list sorted as well.
思路:
在原链表head的前面,加一个super head,这样操作起来更方便一些。我运气不错,提交一次就通过了。
代码实现:
注意:代码没有考虑内存泄漏问题,按理讲是应该考虑的。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNextAllSameVal(ListNode *pre){
int val = pre->next->val;
while (pre->next && pre->next->val == val){
pre->next = pre->next->next;
}
}
ListNode* deleteDuplicates(ListNode* head) {
if (head == nullptr || head->next == nullptr){
return head;
}
ListNode *superHead = new ListNode();
superHead->next = head;
ListNode *pre = superHead;
ListNode *cur = head;
while (cur && cur->next){
if (cur->val == cur->next->val){
deleteNextAllSameVal(pre);
cur = pre->next;
}else{
pre = pre->next;
cur = cur->next;
}
}
return superHead->next;
}
};
discuss:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL) return NULL;
ListNode *FakeHead = new ListNode;
FakeHead->next = head;
ListNode *pre = FakeHead;;
ListNode *cur = head;
while (cur != NULL){
while (cur->next != NULL && cur->val == cur->next->val){ // cur会停在最后一个重复元素上
cur = cur->next;
}
if (pre->next == cur){ // cur没有动
pre = pre->next; // pre后移
}else{
pre->next = cur->next; // 直接把全部重复元素都跳过了
}
cur = cur->next;
}
return FakeHead->next;
}
};