单链表逆置
链表逆置问题是将链表的第一个元素和最后一个元素互换,第二个元素和倒数第二个元素互换······,直到将
(a1,a2,a3·····an-1,an
)置换成(an,an-1····,a3,a2,a1)
。
图解:
代码实现:
逆置函数片段
void reverse(struct student *head) //链表逆置
{
struct student *p,*q;
p = head->next; //p指向首元结点
head->next = NULL; //链表置空
while(p) //循环
{
q=p; //q指向p
p=p->next ; //p移动到下一个结点
q->next = head->next ; //用头插法插入q结点
head->next = q;
}
}
完整代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct student
{
int number; //学号
char name[20]; //姓名
struct student *next;
};
struct student *init() //头结点初始化
{
struct student *head;
head = (struct student *)malloc(sizeof(struct student));
head->next = NULL;
return head;
}
void Creat(struct student *head) //链表的创建(尾插法)
{
struct student *s,*r;
r = head;
int num;
char name[20];
while(1)
{
printf("please input the name:\n");
scanf("%s",name);
printf("please input the number:\n");
scanf("%d",&num);
if(num <= 0)
{
break;
}
s = (struct student *)malloc(sizeof(struct student));
strcpy(s->name ,name);
s->number = num;
//尾插法
r->next = s;
r = s;
}
s->next = NULL;
}
void print(struct student *head) //打印
{
struct student *temp = head->next ;
printf("******信息如下:******\n");
while(temp)
{
printf("%s\n",temp->name);
printf("%d\n",temp->number );
printf("\n");
temp = temp->next ;
}
}
void reverse(struct student *head) //链表逆置
{
struct student *p,*q;
p = head->next; //p指向首元结点
head->next = NULL; //链表置空
while(p) //循环
{
q=p; //q指向p
p=p->next ; //p移动到下一个结点
q->next = head->next ; //用头插法插入q结点
head->next = q;
}
}
int main()
{
int n;
struct student *head = init(); //初始化
Creat(head); //链表创建
print(head); //打印
reverse(head); //链表逆置
print(head);
}
运行结果
: