单链表的逆序存储
在实际应用中,经常需要用到逆序存储。而当使用链表时,逆序存储的优势更加突出,在这里,我将实现单链表的逆序存储,并且还将实现顺序存储,用以比较。
代码部分:
//逆序存储
#include<stdio.h>
#include<malloc.h>
struct List {
int data;
struct List *next;
};
struct List * CreatList1(int n);
void print(struct List *L,int n);//打印
int main()
{
struct List *L;
int n;
scanf("%d",&n);
L=CreatList1(n);
print(L,n);
}
//逆序存储的链表
/*例如输入12345
输出54321
*/
struct List * CreatList1(int n)
{
int i;
struct List *p,*L;
L=(struct List *)malloc(sizeof(struct List));
if(L==NULL)
{
printf("error\n");
exit(0);
}
L->next=NULL;//建立一个带有头节点的链表
for (i=n;i>0;i--)
{
p=(struct List *)malloc(sizeof(struct List ));//生成新的节点
if (p==NULL)
{
printf("error\n");
exit(0);
}
scanf("%d",&p->data);
p->next=L->next;//将每一个新节点,插入在头节点之后
L->next=p;
}
return L;
}
void print(struct List *L,int n)
{
struct List *p;
p=L->next;//L为头节点,头节点的数据域没有值
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
运行结果:
//顺序存储
#include<stdio.h>
#include<malloc.h>
struct List {
int data;
struct List *next;
};
void print(struct List *L,int n);//打印
struct List *CreatList2(int n);
int main()
{
struct List *L;
int n;
scanf("%d",&n);
L=CreatList2(n);
print(L,n);
}
//按顺序存储
//例如 输入12345 输出12345
struct List *CreatList2(int n)
{
int i;
struct List *L,*p,*t;
L=(struct List *)malloc (sizeof(struct List ));
if(L==NULL)//内存分配失败
{
printf("error\n");
exit(0);
}
L->next=NULL;
t=L;
for (i=0;i<n;i++)
{
p=(struct List *)malloc(sizeof(struct List ));
if (p==NULL)//内存分配失败
{
printf("error\n");
exit(0);
}
t->next=p;
scanf("%d",&p->data);
p->next=NULL;
t=p;
}
return L;
}
void print(struct List *L,int n)
{
struct List *p;
p=L->next;//L为头节点,头节点的数据域没有值
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
ps:代码中没有加相应提示,可读性教差,见谅!!
通过比较不难看出,所谓的逆序存储,就是将每一次创建的新节点插入在头节点之后。