#include<malloc.h> using namespace std; #define Elemtype int #define Maxsize 50 //帶有頭部節點的鏈棧 typedef struct LinkNode{ Elemtype data; struct LinkNode *next; }*LiStack; //初始化 void InitStack(LiStack &L) { L = (LinkNode*)malloc(sizeof(LinkNode)); L->next = nullptr; } //棧判空 bool StackEmpty(LiStack L) { if(L->next == nullptr) { printf("棧爲空\n"); return false; } else { printf("棧不爲空\n"); return true; } } //入棧 bool Push(LiStack &L,int e) { LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode)); s->data = e; s->next = L->next; L->next = s; return true; } //出棧 bool Pop(LiStack &L,int &e) { if(L->next == nullptr) { printf("棧已空\n"); return false; } LinkNode *p = L->next; e = p->data; L->next = p->next; printf("出棧元素值爲%d\n",e); free(p); return true; } //獲取頂部元素 bool GetTop(LiStack L,int x) { if(L->next == nullptr) { printf("棧已空\n"); return false; } LinkNode *p = L->next; x = p->data; printf("棧頂元素值爲%d\n",x); return true; } //打印棧 void PrintStack(LiStack L) { LinkNode *n = L->next; while(n != nullptr) { printf("|___%d___|\n",n->data); n = n ->next; } } int main() { LiStack s; InitStack(s); StackEmpty(s); Push(s,1); Push(s,2); Push(s,3); Push(s,4); StackEmpty(s); PrintStack(s); int e,x; Pop(s,e); PrintStack(s); GetTop(s,x); return 0; }