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
.
/** * 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 myhead(99), *prev, *s, *e; int cnt; prev = &myhead; myhead.next = head; s = head; while (s != NULL) { e = s->next; cnt = 0; while (e != NULL && e->val == s->val) e = e->next, cnt++; if (cnt == 0) { prev = s; s = e; } else { prev = s; del(s->next, e); s->next = e; s = e; } } return myhead.next; } void del(ListNode* s, ListNode* e) { // delete [s, e); ListNode *t; while (s != e) { t = s; s = s->next; delete t; } } };
/** * 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 myhead(99); myhead.next = head; ListNode *prev = &myhead, *cur = head, *next; int cnt; while (cur != NULL) { next = cur->next; cnt = 0; while (next != NULL && next->val == cur->val) next=next->next, cnt++; if (cnt == 0) { prev = cur; cur = next; } else { prev->next = next; del(cur, next); cur = next; } } return myhead.next; } void del(ListNode* s, ListNode* e) { // delete [s, e); ListNode *t; while (s != e) { t = s; s = s->next; delete t; } } };
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
.