栈的基本操作
作者:互联网
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
#define Status int
#define SElemType int
#define ERROR 1
typedef struct StackNode{
ElemType data;
struct StackNode *next;
}StackNode,*LinkStack;//链栈的储存结构
LinkStack S;
LinkStack p;
/*链栈的初始化*/
Status InitStack(LinkStack &S){
S=NULL;
return 1;
}
/*入栈操作*/
Status Push(LinkStack &S,SElemType e){
p=new StackNode;
p->data=e;
p->next=S;
S=p;
return 1;
}
/*出栈操作*/
Status Pop(LinkStack &S,SElemType &e){
if(S==NULL) return ERROR;
e=S->data;
p=S;
S=S->next;
delete p;
return true;
}
/*判断栈是否为空*/
int StackEmpty(LinkStack S){
if(S==NULL) printf("栈为空!");
return 0;
}
///*链栈的清空*/
//Status ClearStack(LinkStack S){
// LinkStack t;
// t=S;
// if(t!=NULL){
// p=t;
// t=t->next;
// delete p;
// }
// else{
// printf("栈为空!");
// }
// return true;
//}
/*取栈顶元素*/
SElemType GetTop(LinkStack S){
if(S!=NULL){
return S->data;
}
}
///*链栈的销毁*/
//void DestoryStack(LinkStack S){
// StackNode *p;
// StackNode *q;
// p=S;
// while(p){
// q=p;
// p=p->next;
// free(q);
// }
//}
//摧毁桟
void Destory_Stack(LinkStack S) {
LinkStack p = S;
LinkStack q;
while (p) {
q = p->next;
delete p;
p = q;
}
printf("销毁成功\n");
}
//摧毁节点
void Destory_SNode(LinkStack Snode) {
delete Snode;
}
void Clear(LinkStack &S) {
LinkStack p = S->next;
LinkStack s;
while (p != NULL) {
s = p;
p = p->next;
Destory_SNode(s);
}
S->next =NULL;
printf("清空成功\n");
}
/*链栈的遍历*/
void StackPrint(LinkStack S){
StackNode *p;
if(S==NULL){
printf("栈为空!\n");
}
printf("栈中元素为:\n");
p=S;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
}
int main(){
int choice;
while(1){
printf("-----链栈的各种基本操作-----\n");
printf("---1.创建链栈(入栈操作)---\n");
printf("---2.出栈操作---\n");
printf("---3.清空链栈---\n");
printf("---4.销毁链栈---\n");
printf("---5.判断链栈是否为空---\n");
printf("---6.取栈顶元素---\n");
printf("---7.退出---\n");
scanf("%d",&choice);
if(choice==7){
printf("退出程序");
break;
}
switch(choice){
case 1:
int e,n;
printf("请输入要创建的栈的长度\n");
scanf("%d",&n);
printf("请分别输入各个元素:\n");
for(int i=0;i<n;i++){
scanf("%d",&e);
Push(S,e);
}
StackPrint(S);
printf("\n");
break;
case 2:
int x;
Pop(S,x);
printf("被删除的栈顶元素是%d\n",x);
printf("栈变为:");
StackPrint(S);
printf("\n");
break;
case 3:
Clear(S);
break;
case 4:
Destory_Stack(S);
break;
case 5:
StackEmpty(S);
break;
case 6:
int k=GetTop(S);
printf("%d\n",k);
break;
}
}
return 0;
}
标签:LinkStack,int,next,---,链栈,printf,基本操作 来源: https://blog.csdn.net/qq_52952960/article/details/121415107