Created
December 4, 2014 07:02
-
-
Save chuchao333/935c0ce4911d243f1dbe to your computer and use it in GitHub Desktop.
Remove Duplicates from Sorted List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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