题目要求参考剑指offer面试题目57
#include<iostream>
using namespace std;
struct Node{
int data;
Node *next;
Node(int value):data(value),next(NULL){}
};
Node *create_link()
{
Node *node1=new Node(1);
Node *head=node1;
Node *p,*q;
for(int i=1;i<=2;++i)
{
p=new Node(2);
if(head->next==NULL)
{
head->next=p;
}
else
{
q->next=p;
}
q=p;
}
for(int i=1;i<=2;++i)
{
p=new Node(3);
if(head->next==NULL)
{
head->next=p;
}
else
{
q->next=p;
//q=p;
}
q=p;
}
Node *node=new Node(4);
q->next=node;
//q->next=head->next->next;
return head;
}
void print(Node *head)
{
/*for(int i=0;i<6;++i)
{
cout<<head->data<<endl;
head=head->next;
}*/
Node *p=head;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
}
Node *delete_duplication(Node **head)
{
if(head==NULL||*head==NULL)
{
return NULL;
}
Node *pre_node=NULL;
Node *cur_node=*head;
while(cur_node!=NULL)
{
bool flag=false;
Node *next=cur_node->next;
if(next!=NULL&&next->data==cur_node->data)
{
flag=true;
}
if(!flag)
{
pre_node=cur_node;
cur_node=cur_node->next;
}
else
{
int value=cur_node->data;//the most important part,we can delete the last node by this value
Node *deleted=cur_node;
while(deleted!=NULL&&deleted->data==value)
{
next=deleted->next;
delete deleted;
deleted=NULL;
deleted=next;
}
if(pre_node==NULL)
{
*head=next;
}
else
pre_node->next=next;
cur_node=next;
}
}
return *head;
}
int main()
{
Node *head=create_link();
delete_duplication(&head);
print(head);
system("pause");
return 0;
}