一、链栈的定义:
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
二、初始化:
Status InitStack(LinkStack &S)
{//构建一个空栈,栈顶指针置空
S=NULL;
return OK;
}
三、入栈:
算法步骤:
①为入栈元素e分配空间,用指针p指向;
②将新节点数据域置为e;
③将新节点插入栈顶;
④修改栈顶指针为p;
Status Push(LinkStack &S,int e)
{//在栈顶插入元素e;
StackNode *p;
p=new StackNode;//生成新的节点
p->data=e;//将新的节点数据域置为e;
p->next=S; //将新的节点插入栈顶;
S=p;//修改栈顶指针p;
return OK;
}
四、出栈:
算法步骤:
①判断栈是否为空,若空则返回ERROR;
②将栈顶元素赋给e;
③临时保存栈顶元素空间,以备释放;
④修改栈顶指针,指向新的栈顶元素;
⑤释放原栈顶元素空间;
Status Pop(LinkStack &S)
{//删除S的栈顶元素,用e返回其值
LinkStack p;
p=new StackNode;
int e;
if(S==NULL) return ERROR;//栈空;
e=S->data;//将栈顶元素赋给e;
p=S;//用p临时保存栈顶元素空间,以备释放;
S=S->next;//修改栈顶指针;
delete p;//释放原栈顶元素空间;
return e;
}
五、取栈顶元素:
算法步骤:
①判断是否为空;
②直接返回栈顶值;
Status GetTop(LinkStack &S)
{//返回S的栈顶元素,不修改栈顶指针;
if(S!=NULL)//栈非空;
return S->data;//返回栈顶元素的值,栈顶指针不变;
}
六、主函数:
int main()
{
LinkStack S;
InitStack(S);
printf("请输入元素个数:");
int x;
scanf("%d",&x);
int e;
printf("请输入元素:");
for(int i=0;i<x;i++){
scanf("%d",&e);
Push(S,e);//在栈顶插入元素e;
}
printf("栈顶元素为:%d",GetTop(S));//返回S的栈顶元素,不修改栈顶指针;
printf("\n");
printf("元素遍历:");
for(int i=0;i<x;i++){
printf("%d ",Pop(S));//删除S的栈顶元素,用e返回其值
}
return 0;
}
七、完整代码:
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct StackNode
{
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
Status InitStack(LinkStack &S)
{//构建一个空栈,栈顶指针置空
S=NULL;
return OK;
}
Status Push(LinkStack &S,int e)
{//在栈顶插入元素e;
StackNode *p;
p=new StackNode;//生成新的节点
p->data=e;//将新的节点数据域置为e;
p->next=S; //将新的节点插入栈顶;
S=p;//修改栈顶指针p;
return OK;
}
Status Pop(LinkStack &S)
{//删除S的栈顶元素,用e返回其值
LinkStack p;
p=new StackNode;
int e;
if(S==NULL) return ERROR;//栈空;
e=S->data;//将栈顶元素赋给e;
p=S;//用p临时保存栈顶元素空间,以备释放;
S=S->next;//修改栈顶指针;
delete p;//释放原栈顶元素空间;
return e;
}
Status GetTop(LinkStack &S)
{//返回S的栈顶元素,不修改栈顶指针;
if(S!=NULL)//栈非空;
{
return S->data;//返回栈顶元素的值,栈顶指针不变;
}
}
int main()
{
LinkStack S;
InitStack(S);
printf("请输入元素个数:");
int x;
scanf("%d",&x);
int e;
printf("请输入元素:");
for(int i=0;i<x;i++){
scanf("%d",&e);
Push(S,e);//在栈顶插入元素e;
}
printf("栈顶元素为:%d",GetTop(S));//返回S的栈顶元素,不修改栈顶指针;
printf("\n");
printf("元素遍历:");
for(int i=0;i<x;i++){
printf("%d ",Pop(S));//删除S的栈顶元素,用e返回其值
}
return 0;
}
八、运行结果: