題意
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Subscribe to see which companies asked this question.
解法
實現
/**
* 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* pre = head;
ListNode* cur = head->next;
ListNode* next = NULL;
while(cur != NULL){
if(pre->val != cur->val){
if(next == NULL){
head = pre;
next = pre;
}else{
next->next = pre;
next = pre;
}
pre = cur;
cur = cur->next;
}else{
while(cur != NULL && cur->val == pre->val) cur = cur->next;
if(cur == NULL && next == NULL) return NULL;
else if(cur == NULL && next != NULL){
next->next = NULL;
return head;
}else if(cur != NULL && next == NULL){
pre = cur;
cur = cur->next;
if(cur == NULL) return pre;
}else{
next->next = cur;
pre = cur;
cur = cur->next;
}
}
}
return head;
}
};