leetcode:单链表之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.
即:给定一个链表,对链表删除重复的数据。
c++实现:
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode (int x):val(x),next(NULL){ }
};
ListNode *createListNode(int arr[],int n)
{
ListNode *r;
ListNode *p;
ListNode * L=(ListNode*)malloc(sizeof(ListNode));
r=L;
for(int i=0;i<n;i++)
{
p=(ListNode*)malloc(sizeof(ListNode));
p->val=arr[i];
r->next=p;
r=p;
}
r->next=NULL;
return L->next;
}
//递归版
//ListNode *deleteDuplicates(ListNode *head)
//{
//
// if(!head||!head->next)
// return head;
// ListNode *p=head->next;
// if(head->val==p->val)
// {
// while(head->val==p->val)
// {
// p=p->next;
// if(!p)break;
// }
// return deleteDuplicates(p);
// }
// head->next=deleteDuplicates(head->next);
// return head;
//}
//迭代版
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL || head->next == NULL)
return head;
// ListNode* dummy_head = new ListNode(-1);//注意:使用new ListNode(-1)创建头结点时,return时为dummy_head->next而不是dummy_head.next.
ListNode dummy_head(-1);
ListNode* tail = &dummy_head;
ListNode* node1 = head;
ListNode* node2 = head->next;
while (node1 != NULL && node2 != NULL )
{
if (node1->val != node2->val)
{
tail->next = node1;
tail = tail->next;
node1 = node2;
node2 = node2->next;
}
else
{
while(node1!= NULL && node1->val == node2->val)
node1 = node1->next;
if (node1 != NULL)
node2 = node1->next;
}
}
if (node1!= NULL && tail->val != node1->val)
{
tail->next = node1;
tail = tail->next;
}
tail->next = NULL;
return dummy_head.next;
}
int main()
{
int a[]={1,1,1,2,3};
ListNode *input;
ListNode *out;
input= createListNode(a,5);
out=deleteDuplicates(input);
while(out != NULL)
{
cout<<out->val;
out = out->next;
}
cout<<endl;
return 0;
}
输出结果: