#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
int n=0;
struct student{ //学生结构体节点
int num;
char name[20];
struct student *next;
};
struct student *creat(){ //链表建立
struct student *head,*p1,*p2;
head=0;
p1=p2=(struct student *)malloc(LEN);
printf("请输入学生ID和姓名,中间以空格隔开,输入0 0结束输入:");
scanf("%d %s",&p1->num,p1->name);
while(p1->num!=0){
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%d %s",&p1->num,p1->name);
}
p2->next=0;
return head;
}
void print(struct student *p){ //链表打印
while(p!=0){
printf("%d %s\n",p->num,p->name);
p=p->next;
}
}
struct student *paixu(struct student *p){
struct student *head,*p1,*p2,*p3;
head=p1=p2=p;
int k=0;
while(p1!=0) {
k++;
if(p1->next!=0){ //没到结尾的情况处理
if(k==1) p1=p1->next; //链表第一个元素的处理
else { p3=p1->next; //以后的元素处理
p1->next=p2;
p2=p1;
p1=p3;}
}
else { //到结尾了 处理完链表头 跳出循环
head->next=0;
head=p1;
p1->next=p2;
break;
}
}
return head;
}
int main()
{ struct student *head=creat(); //调用链表
struct student *head1=paixu(head); //调用逆序排列
print(head1); //打印逆序后的结果
return 0;
}
将一个链表按逆序排列,即将链头当链尾,链尾当链头。
最新推荐文章于 2021-05-24 22:51:32 发布