Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created March 17, 2013 18:00
Show Gist options
  • Save zhoutuo/5182802 to your computer and use it in GitHub Desktop.
Save zhoutuo/5182802 to your computer and use it in GitHub Desktop.
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.
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode preHead(-1);
preHead.next = head;
ListNode* tmp = &preHead;
while(tmp->next != NULL) {
int val = tmp->next->val;
ListNode* post = tmp->next;
while(post->next != NULL and post->next->val == val) {
post = post->next;
}
if(tmp->next != post) {
tmp->next = post->next;
} else {
tmp = tmp->next;
}
}
return preHead.next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment