#include <iostream> using namespace std; /***********************************/ /* 棧的鏈式存儲結構實際上是一個單鏈表,叫鏈棧 插入和刪除操作只能在鏈棧的棧頂進行 */ /***********************************/ #define MaxSize 100 typedef struct Node { int data; struct Node *next; }*pLinkStack, nLinkStack; //鏈表初始化,創建一個有頭結點的鏈表 pLinkStack CreateLinkStack() { pLinkStack s; s = new nLinkStack; s->next = NULL; return s; } int IsEmptyLinkStack(pLinkStack s) { //判斷堆棧s是否為空,若為空則返回1,否則返回0 return (s->next == NULL); } void PushLinkStack(int item, pLinkStack s) { //將元素item壓入堆棧s pLinkStack tempCell; tempCell = new nLinkStack; tempCell->data = item; tempCell->next = s->next; s->next = tempCell; //由於頭結點的存在 } int PopLinkStack(pLinkStack pS) { //刪除並返回堆棧s的棧頂元素 pLinkStack firstCell; int topElem; if ( IsEmptyLinkStack(pS) ) { cout << "LinkStack is empty!" << endl; return NULL; } else { firstCell = pS->next; pS->next = firstCell->next; topElem = firstCell->data; delete firstCell; return topElem; } }