【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,
Given1->2->3->3->4->4->5
, return1->2->5
.
Given1->1->1->2->3
, return2->3
.
题目意思:
凡是给定链表里出现的重复的元素,要一个不留的删掉!!!
解题思路:
这题挺简单的,LeetCode里还有一道题 Remove Duplicates from Sorted List ,这是它的升级版,两个的思路都是差不多的。
使用一个p和一个del指针,p负责遍历链表发现重复元素,del负责指向重复的元素的节点然后删掉他们。
注意,为了处理第一个节点方便,我们增加了一个dummy节点。
代码如下:
1 class Solution { 2 public: 3 bool judgeDuplicates(ListNode *p){ 4 if(p->next == NULL) 5 return false; 6 return (p->val == p->next->val); 7 } 8 9 ListNode *deleteDuplicates(ListNode *head) { 10 if(head == NULL) 11 return NULL; 12 ListNode *dummy = new ListNode(0); 13 dummy->next = head; 14 ListNode *p = dummy,*del = NULL; 15 16 while(p->next != NULL){ 17 if(judgeDuplicates(p->next)){ 18 int val =p->next->val; 19 while(p->next != NULL && p->next->val == val){ 20 del = p->next; 21 p->next = del->next; 22 delete del; 23 } 24 } 25 else{ 26 p = p->next; 27 } 28 } 29 30 del = dummy; 31 dummy = dummy->next; 32 delete del; 33 return dummy; 34 } 35 };
posted on 2014-04-02 21:45 Allen Blue 阅读(103) 评论(0) 编辑 收藏 举报