您的位置:首页 > 其它

[LeetCode] Remove Duplicates from Sorted List、Remove Duplicates from Sorted List II

2013-08-20 21:53 483 查看
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) {}
* };
*/
#define LN ListNode
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

const int INVALID =INT_MAX;
LN guard(INVALID);
guard.next=head;
LN* pre=&guard;
LN* cur=head;
while(cur)
{
if ( cur->val == pre->val )
{
pre->next=cur->next;
delete cur;
cur=pre->next;
}
else
{
pre=pre->next;
cur=cur->next;
}
}
return guard.next;
}
};


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) {}
* };
*/
#define LN ListNode
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

const int INVALID=INT_MAX;
LN guard(INVALID);
guard.next=head;

LN* pTail=&guard;
LN* cur=head;
while(cur)
{
if ( cur->next==NULL || cur->val!=cur->next->val)
{
pTail->next=cur;
pTail=pTail->next;
cur=cur->next;
}
else
{
int v=cur->val;
while(cur&&cur->val==v)
{
pTail->next=cur->next;
delete cur;
cur=pTail->next;
}
}
}
return guard.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: