Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save pdu/4586082 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4586082 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. http://leetcode.com/onlinejudge#question_82
/**
* 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* prev = NULL;
ListNode* cur = head;
while (cur != NULL) {
int cnt = 0;
int val = cur->val;
while (cur != NULL && cur->val == val) {
cur = cur->next;
cnt++;
}
if (cnt == 1) {
ret->val = val;
prev = ret;
ret = ret->next;
}
}
if (prev != NULL)
prev->next = NULL;
else
head = NULL;
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment