题目描述
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 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==NULL||head->next==NULL)
return head;
ListNode* L=new ListNode(0);
L->next=head;
//建立快慢指针
ListNode* slow=L;
while(slow->next)
{
ListNode* fast=slow->next;
while(fast->next && fast->val==fast->next->val )
{
fast=fast->next;
}
if(slow->next==fast)
slow=slow->next;
else
{
slow->next=fast->next;
}
}
return L->next;
}
};
//思路是相同的,两次编写
/**
* 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* new_head = new ListNode(0);
ListNode* cur = new_head;
ListNode* temp1=head;
while(temp1)
{
ListNode* temp2=temp1->next;
if(!temp2)
{
cur->next = temp1;
temp1=temp1->next;
cur=cur->next;
}
else if(temp2 && temp1->val != temp2->val)
{
cur->next = temp1;
temp1=temp1->next;
cur = cur->next;
}
else
{
while(temp2 &&temp1->val == temp2->val)
{
temp2=temp2->next;
}
temp1=temp2;
}
}
cur->next =NULL;//这里不可忘记,否则没有起到结束,例如输入[1,2,2],没有此句,则输出[1,2,2]
return new_head->next;
}
};