您的位置:首页 > 编程语言 > C语言/C++

【Remove Duplicates from Sorted List 】cpp

2015-06-27 22:15 363 查看
题目:

第一次刷的时候漏掉了这道题。

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) {
if ( !head ) return head;
ListNode dummpy(-1);
dummpy.next = head;
ListNode* pre = head;
ListNode* curr = head->next;
while (curr)
{
if ( curr->val!=pre->val )
{
pre = curr;
curr = curr->next;
}
else
{
pre->next = curr->next;
curr = curr->next;
}
}
return dummpy.next;
}
};


tips:

纠结了一下才AC。原因是第一次写的时候:

pre = curr;
curr = curr->next;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: