c语言链表反转函数 c语言反转单链表

C语言用链表实现逆序输出#includestdio.h
#includestdlib.h
#include malloc.h
//定义链表节点
typedef struct LNode
{ int data;
struct LNode *next;
} LNode, *Linklist;
//创建链表
Linklist create()
{ int i,n; //i用于下面循环,n用来存放有效节点的字数
Linklist p,L;
printf("Please input N =");
scanf("%d",n);
L= (Linklist)malloc(sizeof(LNode)); // 分配一个不存放有效数据的头结点
L-next=NULL;
for(i = 0; in; i)
{ p = (Linklist)malloc(sizeof(LNode));//生成新节点
scanf("%d",p-data);//输入元素值
p-next = L-next;
L-next = p;
}
return L; //返回头节点 ;
}
//链表反转输出
Linklist ReverseList(Linklist L,int st)//st为1时输出结点数据
{ if(L-next!= NULL)
ReverseList(L-next,1);
if(st)printf("%d ", L-data);
return L;
}
void put(Linklist L)
{ Linklist p;
p = L-next;
while(p != NULL)
{ printf("%d ", p-data);
p = p-next;
}
printf("\n");
}
int main()
{ Linklist L;
L=create();
printf("A: "); put(L);
printf("B: ");
ReverseList(L,0);//附加结点未保存数据,故第二参数为0
return 0;
}
c语言,链表的反转,请写出代码,并讲解下,谢了?。。。。?/h2>扣着的是头节点(头子)
车是首节点(首子)
马是次节点(次子)
牙签细的是指针指向,香头发黑的是指向,铁头细的是指向 。
根据步骤写程序的伪算法(3步4循环,7张图片搞定),如下:
以下是while循环(条件:香头指向不为空)
第一个循环把马弄到车前面,
第二个循环把相弄到马前面
第三个循环把士弄到相前面
........
直到香指向为空后停止循环 。
代码如下:只需要一个首结点pHead,就能把链表找到 , 并倒置 。具体代码如下
p香=pHead-pNext;
p铁=p香-pNext;
p香-pNext=NULL;
P香=p铁
while(p香 !=NULL)
{
p铁=p香-pNext;
p香-pNext=pHead-pNext;
pHead-pNext=p香;
p香=p铁;
}
对照伪算法(三步四循环) , 和上面的代码是一一对应的:
第一步:香头指向首子 , 铁头指向次子
第二步:删掉首子指向次子(铁头所指向的那个子)的牙签
第三步:香头跟着铁头
以下循环条件:(条件:香头指向不为空)
{
循环1:铁头移动到香头的下一个指向
循环2:香头的下一个指向首子
循环3:头子的下一个跟着香头
循环4:香头跟着铁头
}
自己用道具操作几遍 , 然后把流程背会,以后自己根据流程写代码即可 。
用C语言,自定义结构体及函数,完成单向链表数据的反转 。#include stdio.h
#include stdlib.h
struct list
{
int data;
struct list* next;
};
/*创建单链表,此处为了示范,仅自动创建几个节点*/
struct list* create()
【c语言链表反转函数 c语言反转单链表】{
struct list *head = NULL, *p, *q;
int i;
head = p = (struct list*)malloc(sizeof(struct list));
p-data = https://www.04ip.com/post/0;
for (i = 1; i = 10; i)
{
q = (struct list*)malloc(sizeof(struct list));
q-data = https://www.04ip.com/post/i;
p-next = q;
p = q;
}
p-next = NULL;
return head;
}
/*顺序输出单链表的所有值*/
void print(struct list* head)
{
struct list* p = head;
if (!head) puts("NULL");
while (p)
{
printf("%d ", p-data);
p = p-next;
}
}
/*反转单链表*/
struct list* reverse(struct list* head)
{
struct list *p = head, *q, *t;
if (!head) return NULL;
q = p-next;
while (q)
{
t = q-next;
q-next = p;
p = q;
q = t;
}
head-next = NULL;
head = p;
return head;
}
int main(void)
{
struct list* head;
head = create();
head = reverse(head);
print(head);
return 0;
}
C语言链表反转问题最基础的问题,函数参数传递是值传递,不会改变实参的值的,void ReverseList(Student* pHead)这样写参数是引用类型,可以改变实参的值
C语言原地逆转单链表List_ptr InvertList(List_ptrhead) //原地逆转单链表head
{
List_ptr p=head,q=NULL,listend=head;
while(listend-next!=NULL) listend=listend-next;
while(p!=listend)
{
head=p-next;
listend-next=p;
if(q==NULL) p-next=NULL;
else p-next=q;
q=p;
p=head;
}
return head;
}
c语言数据结构链表反转两处scanf("%c",data);后面都要加一行getchar();
另外代码中c语言链表反转函数的%s要改成%c
关于c语言链表反转函数和c语言反转单链表的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读