【数据结构】链式栈的实现(C语言)
栈的链式存储称为链式栈,链式栈是一种特殊的单链表,它的插入和删除规定在单链表的同一端进行。链式栈的栈顶指针一般用top表示。(个人理解:相当于只对单链表的第一个结点进行操作)
链式栈要掌握以下基本操作:
1、建立一个空链式栈
2、判断链式栈是否为空
3、读链式栈的栈顶节点值
4、输出链式栈中个结点的值
5、向链式栈中插入一个值为x的结点(进栈)
6、删除链式栈的栈顶结点(出栈)
运行环境:Dev-C++5.11
以下是头文件:
#ifndef LNKSTACK_H_INCLUDED
#define LNKSTACK_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
typedef struct link_node
{
int info;
struct link_node *next;
}N;
/*创建一个空的链式栈*/
N *init()
{
return NULL;
}
/*对链式栈进行初始化*/
N *creat(N *top)
{
int x;
N *p;
printf("以输入-1为结束\n");
scanf("%d",&x);
while(x!=-1)
{
p=(N*)malloc(sizeof(N));
p->info=x;
p->next=top;
top=p;
scanf("%d",&x);
}
return top;
}
/*判断链式栈是否为空*/
int isempty(N *top)
{
return (top?0:1);/*返回1这说明是空*/
}
/*取得链式栈的栈顶结点值*/
int read(N *top)
{
if(!top)
{
printf("\n该链式栈是空的\n");exit(1);
}
return top->info;
}
/*输出链式栈中各结点的值*/
void display(N *top)
{
N *p=top;
if(!top)
{
printf("该链式栈是空的\n");
}
else
{
while(p)
{
printf("%d ",p->info);
p=p->next;
}
}
}
/*链式栈的插入操作*/
N *insert(N *top,int x)
{
N *q=top,*p;
p=(N*)malloc(sizeof(N));
p->info=x;
p->next=top;
top=p;
return top;
}
/*链式栈的删除操作*/
N *dele(N *top)
{
N *p=top;
if(!top)
{
printf("\n该链式栈是空的,无法进行删除\n");return NULL;
}
top=top->next;
free(p);
return top;
}
#endif // LNKSTACK_H_INCLUDED
以下是主程序:
#include "stdio.h"
#include "lnkstack.h"
int main ()
{
int x;
N *p,*q,*top;
while(1)
{
top=init();
top=creat(top);
display(top);
printf("\n插入的数为:");
scanf("%d",&x);
top=insert(top,x);
display(top);
printf("\n删除操作:");
top=dele(top);
display(top);
printf("\n判断链式栈是否为空:");
if(isempty(top))
{
printf("是\n");
}
else
{
printf("否\n");
}
printf("获取链式栈的栈顶结点值:%d\n\n",read(top));
}
return 0;
}