棧是一種只能在一端進行刪除和插入操作的線性表,棧的主要特點是“先進后出”。
順序棧:分配一塊連續的存儲區域存放棧中元素,並用一個變量指向當前的棧頂。
#include <stdio.h> #define MAXSIZE 50 typedef int elemType; typedef struct{ elemType data[MAXSIZE]; int top; }SqStack; //初始化棧 void init(SqStack &stk){ stk.top=-1; } //判斷棧是否為空 bool stackEmpty(SqStack stk){ return stk.top==-1; } //入棧 int push(SqStack &stk,elemType e){ if(stk.top==MAXSIZE-1) return 0; stk.top++; stk.data[stk.top]=e; return 1; } //出棧 int pop(SqStack &stk,elemType &x){ if(stk.top==-1) return 0; x=stk.data[stk.top]; stk.top--; return 1; } //取棧頂元素 int getTop(SqStack stk,elemType &x){ if(stk.top==-1) return 0; x=stk.data[stk.top]; return 1; }
鏈棧:采用鏈式存儲結構存儲棧,棧的所有操作都是在單鏈表的表頭進行的。
typedef int elemType; typedef struct linknode{ elemType data; struct linknode *next; }*LStack; //初始化 帶頭節點的鏈棧 void init(LStack &stk){ stk=(linknode*)malloc(sizeof(linknode)); stk->next=NULL; } //判斷是否為空 int isEmpty(LStack stk){ return stk->next==NULL; } //入棧 int push(LStack &stk,elemType e){ linknode *node = (linknode*)malloc(sizeof(linknode)); if(node==NULL) return 0; node->data=e; node->next=stk->next; stk->next=node; return 1; } //出棧 int pop(LStack &stk,elemType &x){ if(stk->next==NULL) return 0; linknode *node = stk->next; x=node->data; stk->next=node->next; free(node); return 1; } //獲取棧頂元素 int getTop(LStack stk,elemType &x){ if(stk->next==NULL) return 0; x=stk->next->data; return 1; } //清空棧中元素 void clear(LStack &stk){ linknode *node = stk->next; while(node!=NULL){ stk->next=node->next; free(node); node=stk->next; } }
