03
08/2015
[LeetCode] Remove Duplicates from Sorted List II
Remove Duplicates from Sorted List II
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
.
解题思路:
这道题的题意是删除有序链表中所有出现两次或两次以上的元素。本身没有较大的难度,注意第一个元素可能是重复元素的情况。
/** * 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=new ListNode(0); ListNode* tail = myHead->next; ListNode* preTail = myHead; ListNode* p = head, *q; while(p!=NULL){ if(tail==NULL){ tail = p; preTail->next = tail; p=p->next; tail->next = NULL; }else if(tail->val != p->val){ tail->next = p; p=p->next; tail = tail->next; tail->next = NULL; preTail = preTail->next; }else{ while(p!=NULL && tail->val == p->val){ q = p; p=p->next; delete q; } delete tail; tail = NULL; preTail->next=NULL; } } p=myHead; myHead = myHead->next; delete p; return myHead; } };
0 条评论