#include<stdio.h>
#include<stdlib.h>
struct a
{
int data;
struct a*next;
} ;
void list(struct a*p)
{
while(p->next->next!=NULL)
{
printf("%d ",p->next->data);
p=p->next;
}
printf("%dn",p->next->data);
}
struct a*sr( int n)
{
struct a*p,*head,*tail,*p1,*p2;
head=(struct a*)malloc(sizeof(struct a));
int i;
head->next=NULL;
for(i=0;i<n;i++)
{
p=(struct a*)malloc(sizeof(struct a));
scanf("%d",&p->data);
p->next=head->next;//输入的时候就进行了逆置;
head->next=p;
}
printf("%dn",n);
list(head);
tail=head->next;//尽量减少复杂程度,用tail直接=head->next方便一些;
while(tail!=NULL)
{
p2=tail;//当tail需要改变的时候直接p2来改变,这样就不会改变外循环导致混乱了;
p1=tail->next;
while(p1!=NULL)
{
if(tail->data==p1->data)//这里的tail是不会改变的,因为这是内循环,所以只改变他的等价标记p2,(这里错了很多次,是因为tail的改变)
{
p2->next=p1->next;//删除重复的数字,保证数列的不同;
free(p1);//释放空间是一个好习惯;
p1=p2->next;//保证p1可以后移一位数;
n--;
}
else
{
p1=p1->next;//如果不相同就后移一位;
p2=p2->next;
}
}
tail=tail->next;
}
printf("%dn",n);
list(head);
return head;
}
int main()
{
int n;
scanf("%d",&n);
sr(n);
return 0;
}
一开始写的时候,内外循环非常混乱,不知道应该怎么弄,多次调试都是错误;后来经过同学的指导,发现原来是内循环中把tail给改变了啊,导致外循环的混乱,后来用p2代替tail进行向后移一位,就行了。(自我感知:应该清楚弄清楚循环的目的,变量的联系;还有就是尽量写简单的代码,这样差查码也方便;一定要养成好的编程习惯!)
连接http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2122&cid=1134