之前写过数组的方法,现在学了链表,自己试着用链表写了一份代码
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct sort)
struct sort{
int num;
struct sort *next;
}sort1;
int n;
int main()
{
struct sort *creat();//建表
struct sort *p1,*p2;
int i,cnt=0;
p1=p2=creat();
/* do{
printf("%d",p1->num);
p1=p1->next;
}while(p1!=NULL);测试用,其中1到13代表序号,环形链表是一个死循环*/
p1=p1->next;
for(i=1;;i++){
p1=p1->next;
if(i>1){
p2=p2->next;
}
if(i%2==0){//中间空的是要‘删除’的那位,做完再将p1后移一位,中间始终空一位
p2->next=p1;
p1=p1->next;
n--;
}if(n<=2){
break;
}
}
for(i=0;i<2;i++){
printf("%d ",p2->num);
p2=p2->next;
}
}
struct sort *creat()
{
struct sort *head,*p1,*p2;
n=0;
do{
n++;
if(n==1){
head=p1=p2=malloc(LEN);
scanf("%d",&p1->num);//输入1到n代表人数和他们的序号
}else{
p2->next=p1;
}
p2=p1;
p1=malloc(LEN);
scanf("%d",&p1->num);
}while(p1->num!=0);
p2->next=head;
return head;
}