链式栈的定义其实和链表的定义是一样的,只不过在进行链式栈的操作时要遵循栈的规则----即“先进后出”。
1.链式栈的定义
typedef struct StackNode
{SElemType data;struct StackNode *next;
}StackNode,*LinkStack;
2.链式栈的初始化
Status InitStack(LinkStack &S){//链式栈的初始化S=NULL;//构造一个空栈S,将栈顶指针置空return OK;
}
3.入栈操作
Status Push(LinkStack &S,SElemType e){//元素入栈StackNode *p;p=new StackNode;p->data=e;p->next=S;S=p;return OK;
}
4.出栈操作
Status Pop(LinkStack &S,SElemType &e){//元素出栈if(S==NULL) return ERROR;e=S->data;StackNode *p;p=S;S=S->next;delete p;return OK;
}
5.获取栈顶元素
Status GetTop(LinkStack S){//获取栈顶元素if(S!=NULL) return S->data;
}
6.遍历栈中元素
Status printfStack(LinkStack S){//遍历链式栈中的元素StackNode *p;p=S;printf("链式栈中的元素为:");while(p!=NULL){printf("%d ",p->data);p=p->next;}printf("\n");
}
7.获取栈的长度
int StackLength(LinkStack S){//获取栈的长度StackNode *p;p=S;int count=0;while(p!=NULL){count++;p=p->next;}printf("栈的长度为:%d\n",count);
}
8.判断栈是否为空
Status StackEmpty(LinkStack S){//判断链式栈是否为空if(S==NULL) return ERROR;return OK;
}
9.主程序代码
#include<stdio.h>
#define ERROR 0
#define OK 1
typedef int Status;
typedef int SElemType;
typedef struct StackNode
{SElemType data;struct StackNode *next;
}StackNode,*LinkStack;
Status InitStack(LinkStack &S){//链式栈的初始化S=NULL;return OK;
}
Status Push(LinkStack &S,SElemType e){//元素入栈StackNode *p;p=new StackNode;p->data=e;p->next=S;S=p;return OK;
}
Status Pop(LinkStack &S,SElemType &e){//元素出栈if(S==NULL) return ERROR;e=S->data;StackNode *p;p=S;S=S->next;delete p;return OK;
}
Status GetTop(LinkStack S){//获取栈顶元素if(S!=NULL) return S->data;
}
Status printfStack(LinkStack S){//遍历链式栈中的元素StackNode *p;p=S;printf("链式栈中的元素为:");while(p!=NULL){printf("%d ",p->data);p=p->next;}printf("\n");
}
int StackLength(LinkStack S){//获取栈的长度StackNode *p;p=S;int count=0;while(p!=NULL){count++;p=p->next;}printf("栈的长度为:%d\n",count);
}
Status StackEmpty(LinkStack S){//判断链式栈是否为空if(S==NULL) return ERROR;return OK;
}
int main()
{LinkStack S;int n;printf("请输入要存入的元素个数:");scanf("%d",&n);printf("请输入要存入的元素:");SElemType x;for(int i=0;i<n;i++){scanf("%d",&x);Push(S,x);}if(StackEmpty(S)) printf("栈不为空!\n");else printf("栈为空!\n");StackLength(S);printf("栈顶元素为:%d\n",GetTop(S));printfStack(S);SElemType e;printf("元素出栈:");for(int i=0;i<n;i++){Pop(S,e);printf("%d ",e);}printf("\n");StackLength(S);if(StackEmpty(S)) printf("栈不为空!\n");else printf("栈为空!\n");return 0;
}
运行结果
英国有句谚语叫“April showers bring May flowers.”翻译过来就是——四月的雨水带来五月的鲜花。即“苦尽甘来”之意。希望大家生活带甜,幸福开心。