反转链表
#include<stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* ReverseList(struct node* pHead ) {
// write code here
struct node *pre = NULL;
struct node *cur = pHead;
struct node *nex = NULL; // 这里可以指向nullptr,循环里面要重新指向
while (cur) {
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}
int main(){
struct node *head=NULL,*p,*q,*t, *last=NULL;
int a=0;
for(int i=1;i<=3;i++)//循环读入3个数
{
scanf("%d",&a);
p=(struct node *)malloc(sizeof(struct node));//动态申请一个空间,用来存放一个结点,并用临时指针p这个结点
p->data=a;//将数据存储到date数据域中
p->next=NULL;//设置当前结点的后继指针指向空
if(head==NULL)
head=p;//如果这是第一个创建的结点,则把指针指向这个点
else
q->next=p;
//如果不是第一个创建的结点,则将上一个结点的后继指针指向当前结点
q=p;//指针q指向当前结点
}
last=q;
last->next = NULL;
head=ReverseList(head);
t=head;
printf("表是:");
while(t!=NULL)
{
printf("%d ",t->data);
t=t->next;//指向下一个结点数据域
}
t=head;
while(t!=NULL)
{
free(t);
t=t->next;
}
}
本文详细介绍了如何使用C语言实现链表的反转操作,通过递归和指针技巧,一步步演示了从头结点到尾节点的转换过程。通过实例展示了链表节点的创建、输入数据以及最后的逆序显示。
563

被折叠的 条评论
为什么被折叠?



