Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
40 lines (36 sloc) 874 Bytes
problem:
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.
-------------------------------------------------------
solution:
//因为要涉及到删除头结点,所以需要使用二级指针
//////////////////////////////
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *deleteDuplicates(ListNode *head)
{
ListNode *root = NULL;
ListNode **ppNext = &root;
while(head)
{
if(head->next == NULL || head->next->val != head->val)
{
*ppNext = head;
ppNext = &(head->next);
head = head->next;
}
else
{
int val = head->val;
while(head != NULL && head->val == val)
head = head->next;
}
}
*ppNext = NULL;
return root;
}