逆序建立链表,p从head->next开始遍历,q是前驱指针,r是后驱指针,比较r和p,相同删r。
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
int n;
struct node *head,*p,*q,*r;
void reverse_order_list(int n);
void print();
void del();
int main()
{
cin>>n;
reverse_order_list(n);
cout<<n<<endl;
print();
del();
cout<<endl<<n<<endl;
print();
return 0;
}
void print()
{
p=head->next;
while(p)
{
cout<<p->data;
if(p->next)
cout<<" ";
p=p->next;
}
}
void reverse_order_list(int n)
{
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
for(int i=0; i<n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
cin>>p->data;
p->next=head->next;
head->next=p;
}
}
void del()
{
p=head->next;
while(p)
{
q=p;
r=q->next;
while(r)
{
if(p->data==r->data)
{
q->next=r->next;
r=q->next;
n--;
}
else
{
q=q->next;
r=r->next;
}
}
p=p->next;
}
}