链表逆序

bh单链表逆序详解

1、具有链表头的单链表
一段单链表逆序的程序
typedef struct student
{
int number;
char name[20];
int score;
struct student*next;
}student;


student *reverse(student *stu)
{
student *p1,*p2,*p3;
if(stu == NULL||stu->next == NULL)
return stu;
p1=stu->next;//p1指向链表头节点的下一个节点
p2=p1->next;
p1->next=NULL;
while(p2)
{
p3=p2->next;
p2->next = p1;
p1=p2;
p2=p3;
}
printf("p1 =%d,next = %d\n ",p1->number,p1->next->number);
stu->next=p1;//将链表头节点指向p1
return stu;
}

分析:
假设需要逆序的单链表为:


则逆序以后的链表为:


过程:
(1)取p1指向header->nextp1=stu->next;
p2保留p1->nextp2=p1->next;
将p1->next置为NULL,因为单链表逆序以后,当前的p1节点为尾节点 p1->next=NULL;



(2)取p3保留p2->nextp3=p2->next;
将p2插入p1之前p2->next = p1;
p1指向p2指向的节点 p1=p2;
p2指向p3指向的节点p2=p3;




循环一次修改以后的单链表如下:



(3)重复步骤(2)


循环一次修改以后的单链表如下:



(4)将header->next指向p1,完成整个单链表的逆序




2、无链表头的单链表
一段单链表逆序的程序
typedef struct student
{
int number;
char name[20];
int score;
struct student*next;
}student;


student *reverse2(student *stu)
{
student *p1,*p2,*p3;
if(stu == NULL ||stu->next == NULL)
return stu;
p1=stu;//p1指向链表的第一个节点
p2=p1->next;
p1->next = NULL;
while(p2)
{
p3=p2->next;
p2->next = p1;
p1=p2;
p2=p3;
}
printf("p1 = %d,next = %d\n ",p1->number,p1->next->number);
stu=p1;//将链表第一个节点指向p1
return stu;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值