資料結構----鏈棧
阿新 • • 發佈:2018-12-15
鏈棧儲存結構
鏈棧的儲存結構跟單鏈表相同,但是由於只能在棧頂執行插入和刪除操作,顯然以單鏈表的頭部做棧頂最方便,不必要想單鏈表那樣為了運算方便而附加頭結點。
鏈棧的實現
#include<stdio.h> #include<stdlib.h> typedef int DataType; //定義鏈棧的結構體 typedef struct Node{ DataType data; struct Node * next; }Node; //初始化鏈棧 void InitStrack(Node * top){ top = NULL; } //鏈棧的銷燬 void DestroyStrack(Node * top){ Node * p; while(top != NULL){ p = top; top = top->next; free(p); } } //入棧操作 //頭插法進行入棧 Node * Push(Node * top,DataType x){ printf("入棧操作前的top地址%p\n",top); Node * s = (Node *)malloc(sizeof(Node)); s->data = x; s->next = top; top = s; printf("入棧操作後的top地址%p",top); printf("\n"); return top; } //出棧操作 int Pop(Node * top,DataType * ptr){ printf("出棧操作前的top地址:%p\n",top); Node * p = top; if(top == NULL){ printf("下溢錯誤,刪除失敗\n"); return 0; } *ptr = top->data; top = top->next; free(p); printf("出棧操作後的top地址:%p\n",top); return 1; } //取棧頂元素 int GetTop(Node * top, DataType * ptr){ if(top == NULL){ printf("下溢錯誤,取棧頂失敗\n"); return 0; } *ptr = top->data; printf("函式中取棧頂元素%d\n",top->data); return 1; } //判空操作 int Empty(Node * top){ printf("top指標地址%p\n",top); if(top == NULL){ return 1; }else{ return 0; } } //鏈棧的使用 int main(){ DataType x; Node * top = NULL; InitStrack(top); printf("對1 2 3進行入棧操作\n"); top = Push(top,10); top = Push(top,20); top = Push(top,30); top = Push(top,40); //進行出棧操作 if(Pop(top,&x) == 1) { printf("出棧的元素為%d\n",x); } if(Empty(top) == 1){ printf("棧為空\n"); }else{ printf("棧非空\n"); } return 0; }