Skip to content

Instantly share code, notes, and snippets.

@chuchao333
Created December 4, 2014 07:02
Show Gist options
  • Save chuchao333/935c0ce4911d243f1dbe to your computer and use it in GitHub Desktop.
Save chuchao333/935c0ce4911d243f1dbe to your computer and use it in GitHub Desktop.
Remove Duplicates from Sorted List
/**
* 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) {
auto p = head;
// what's the loop invariant here?
while (p != NULL) {
auto q = p -> next;
while (q != NULL && q->val == p->val) {
q = q -> next;
}
// are we required to free those deleted nodes?
p -> next = q;
p = q;
}
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment