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.
解答:我这么做很丑陋,但是要考虑很多情况,其实会有更好的做法的。
之所以temp=head->val+2;而不是加减1,是因为要解决第一个数是INT_MIN,第二个数是INT_MAX的问题,因为最小值减一就是最大值。
/**
* 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* newhead=new ListNode(0);
ListNode* p=newhead;
newhead->next=NULL;
int temp;
if(head&&head->next)
{
if(head->val>head->next->val)
temp=head->val+2;
else
temp=head->val-2;
}
while(head)
{
if((head->val!=temp))
{
if(head->next)
{
if((head->val!=head->next->val))
{
p->next=head;
p=p->next;
}
else
{
temp=head->val;
}
}
else
{
p->next=head;
p=p->next;
}
}
else
{
temp=head->val;
}
head=head->next;
}
p->next=NULL;
return newhead->next;
}
};
二刷时发现这个做法更好,其实我也没怎么做出来的。
要注意
精妙之处在于
”’
if(pre->next==cur)
else
”’
这条语句。
这是用来判断我们要链接的下一个节点是经过很多次重复节点往前走得来的,还是说没有重复节点,要连接。
/**
* 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* newhead= new ListNode(0);
ListNode* pre=newhead;
newhead->next=head;
while(pre->next)
{
ListNode* cur=pre->next;
while(cur->next&&cur->next->val==cur->val) cur=cur->next;
if(pre->next==cur) pre=pre->next;
else pre->next=cur->next;
}
return newhead->next;
}
};