Created
January 21, 2013 13:40
-
-
Save pdu/4586121 to your computer and use it in GitHub Desktop.
Given a sorted linked list, delete all duplicates such that each element appear only once. For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3. http://leetcode.com/onlinejudge#question_83
This file contains hidden or 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) { | |
| ListNode* ret = head; | |
| ListNode* cur = head; | |
| ListNode* prev = NULL; | |
| while (cur != NULL) { | |
| if (cur->next == NULL || cur->val != cur->next->val) { | |
| ret->val = cur->val; | |
| prev = ret; | |
| ret = ret->next; | |
| } | |
| cur = cur->next; | |
| } | |
| if (prev != NULL) | |
| prev->next = NULL; | |
| return head; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment