您好,登錄后才能下訂單哦!
#include<stdio.h> #include<malloc.h> #include<stdlib.h> //動態棧,由鏈表實現 ,上面節點指向下面一個節點 //結構體:節點(表示一個元素) typedef struct Node { int data; struct Node * pNext; }NODE,*PNODE; //結構體:棧,棧頂節點的指針,棧底節點指針(棧底指針指向棧底節點的下一個存儲空間,因為是初始化的時候分配的空間,此時還沒有插入節點)。 typedef struct Stack { PNODE pTop; PNODE pButtom; } STACK,*PSTACK; //為棧分配內存 void init(PSTACK pStack); //壓棧 void push(PSTACK pStack,int val); //遍歷 void traverse(PSTACK pStack); //彈棧,把出棧的節點的數據存入給定的變量中(給地址) bool pop(PSTACK pStack,int * val); int main(void) { //初始化 STACK stack; init(&stack); //壓棧 push(&stack,1); push(&stack,2); push(&stack,3); push(&stack,4); //遍歷 traverse(&stack); //彈棧 int a = 0; pop(&stack,&a); printf("\n出棧的元素是:%d\n",a); //遍歷 traverse(&stack); getchar(); return 0; } //初始化棧 void init(PSTACK pStack) { //為節點分配內存 pStack->pTop = (PNODE)malloc(sizeof(NODE)); if(pStack->pTop == NULL) { printf("動態內存分配失敗!\n"); exit(-1); }else { //棧頂指針和棧底指針相等 ,都指向初始節點 pStack->pButtom = pStack->pTop; pStack->pTop->pNext = NULL; //初始節點的下個節點為NULL } } //壓棧 void push(PSTACK pStack,int val) { //創建一個節點 PNODE pNewNode= (PNODE)malloc(sizeof(NODE)); pNewNode->data = val;//數據域賦值 pNewNode->pNext = NULL;//指針域為空(棧頂) pNewNode->pNext = pStack->pTop;//新加入的節點的下一個節點指向原來的棧頂節點 pStack->pTop = pNewNode;//棧頂指針指向新壓入的節點 return; } //遍歷 void traverse(PSTACK pStack) { PNODE pNode = pStack->pTop; while(pNode != pStack->pButtom) { printf("%d\t",pNode->data); pNode = pNode->pNext; } } //彈棧 bool pop(PSTACK pStack,int * val) { if(pStack->pTop == pStack->pButtom) { return false; } *val = pStack->pTop->data; PNODE r= pStack->pTop;//記錄棧頂節點 pStack->pTop = pStack->pTop->pNext; free(r); r=NULL;//釋放原來棧頂節點的空間 return true; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。