近日,笔者使用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);
}