近日,笔者使用CFree编译器,实现了单链表的就地逆置。
单链表,顾名思义,就是链式存储的线性表,是C与C++的学习中必须掌握的内容之一。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stddef.h>
//笔者个人习惯,将可能使用的头文件均罗列出来
#define OK 1
#define ERROR 0
typedef struct LNode //定义单链表
{
int data;
struct LNode *next;
}LNode,*Linklist;
Linklist jiudinizhi() //执行就地逆置操作的函数
{
Linklist L=NULL;
LNode *p;
int x;
scanf("%d",&x);
while(x!=-1)
{
p=new LNode;
p->data=x;
p->next=L;
L=p;
scanf("%d",&x);
}
return L;
}
int main()
{
Linklist p;
p=jiudinizhi();
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
return (OK);
}
本文介绍了一种使用C/C++实现单链表就地逆置的方法,通过不断调整链表节点的指针方向,使链表的首尾位置互换,达到逆置效果。代码示例清晰,适合初学者理解单链表的特性。
1万+

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



