Remove Duplicates from Sorted List
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 *p; if(!head || !head->next) return head; p=head; while(p->next) { if(p->val==p->next->val) { p->next=p->next->next; } else { p=p->next; } } return head; } };
class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if(head == NULL) return NULL; for (ListNode *prev = head, *cur = head->next; cur; cur = cur->next) { if(prev ->val == cur->val) { prev->next = cur->next; delete cur; } else { prev = cur; } } return head; } };
class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if (!head) return head; ListNode dummy(head->val +1); dummy.next = head; recur(&dummy, head); return dummy.next; } private: static void recur(ListNode *prev, ListNode *cur){ if (cur == NULL) return ; if (prev->val == cur->val) { prev ->next = cur->next; delete cur; return(prev, prev->next); } else { retcur( prev->next, cur->next); } } };
版权声明:本文为博主原创文章,未经博主允许不得转载。