#include <conio.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define IBFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int ElemType; /* 元素类型为int类型*/ //链栈类型 typedef struct LSNode{ ElemType data; //数据域 struct LSNode *next; //指针域 }LSNode, *LStack; //结点和链栈类型 Status InitStack_LS(LStack &S); void DestroyStack_LS(LStack &S); Status StackEmpty_LS(LStack S); Status Push_LS(LStack &S,ElemType e); Status Pop_LS(LStack &S,ElemType &e); Status GetTop_LS(LStack S, ElemType &e); Status Traverse(LStack S); int LengthLStack(LStack S); //链栈的基本操作实现代码如下: //1.初始化链栈 Status InitStack_LS(LStack &S){ S=(LSNode*)malloc(sizeof(LSNode)); if(S==NULL)return OVERFLOW; S->next = NULL; return OK; } //2.销毁链栈 void DestroyStack_LS(LStack &S){ LStack p=S->next,q=S; while(p){ free(q); q=p; p=p->next; } free(p); } //3.判空操作 Status StackEmpty_LS(LStack S){ if(S->next==NULL){ return TRUE; }else{ return FALSE; } } //4.入栈 Status Push_LS(LStack &S,ElemType e){ LSNode *t; t=(LSNode*)malloc(sizeof(LSNode));//为元素e分配空间 if(t==NULL) return FALSE; t->data=e; t->next=S; S=t; return OK; } //5.出栈 Status Pop_LS(LStack &S,ElemType &e){ LSNode *t; if(S==NULL) return ERROR; t=S; //t指向栈顶元素的节点 e=S->data; S=S->next; //删除栈顶结点 free(t); //释放节点t return OK; } //6.取出栈顶元素 Status GetTop_LS(LStack S,ElemType &e){ if(S==NULL) return ERROR; e=S->data; return OK; } //7.链栈的长度 int LengthLStack(LStack S){ int length; while(S->next){ S=S->next; length++; } return length; } //8.遍历栈 Status Traverse(LStack S) { LSNode *p; p = S; while (p->next){ printf("%4d", p->data); p=p->next; } printf("\n"); return OK; } int main(){ int i,e,j,m; LStack S; do{ printf("1.初始化链栈\n"); printf("2.销毁链栈\n"); printf("3.判断链栈是否为空\n"); printf("4.将元素压入栈\n"); printf("5.栈顶元素出栈\n"); printf("6.取栈顶元素,并返回\n"); printf("7.链栈的长度\n"); printf("8.遍历链栈元素\n"); printf("请输入你要进行的操作:\n"); scanf("%d",&i); switch(i){ case 1 : if(InitStack_LS(S)){ printf("初始化成功\n"); printf("请输入5个元素进栈:\n"); for(j=0;j<5;j++){ scanf("%d",&e); Push_LS(S,e); } }else{ printf("初始化失败\n"); } break; case 2 : DestroyStack_LS(S); printf("销毁栈成功\n"); break; case 3 : if(StackEmpty_LS(S)){ printf("链栈为空!\n"); }else{ printf("链栈不为空!\n"); } break; case 4 : printf("请输入压入栈元素的值:\n"); scanf("%d",&e); if(Push_LS(S,e)){ printf("成功压入\n"); }else{ printf("压入失败\n"); } break; case 5 : Pop_LS(S, m); printf("成功出栈,数值为:%d\n",m); break; case 6 : GetTop_LS(S,m); printf("取出栈顶元素的值:%d\n",m); break; case 7 : printf("链栈的长度为:%d\n",LengthLStack(S)); break; case 8 : printf("链表中元素:"); Traverse(S); break; } }while(i>0&&i<=8); return 0; }
时间: 2024-10-13 10:43:01