您好,登錄后才能下訂單哦!
#include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <stdbool.h> typedef struct Node { int data; struct Node * pNext; }NODE, * PNODE; typedef struct Stack { PNODE pTop; PNODE pBottom; }STACK, * PSTACK; //PSTACK等價于struct STACK * void init(PSTACK); //初始化棧 void push(PSTACK, int ); //壓棧 void traverse(PSTACK); //遍歷 bool pop(PSTACK pS,int * pVal); //出棧 void clear(PSTACK pS); //清空棧 int main(void) { STACK S; //STACK等價于struct Stack int val; init(&S); //造出空棧 push(&S, 1); //壓棧 push(&S, 2); push(&S, 3); push(&S, 4); push(&S, 5); push(&S, 6); traverse(&S); //遍歷輸出 /* if(pop(&S,&val)) { printf("出棧成功,出棧的元素是%d\n", val); } else { printf("出棧失敗!\n"); } */ clear(&S); traverse(&S); return 0; } void init(PSTACK pS) { pS->pTop = (PNODE)malloc(sizeof(NODE)); if(NULL == pS->pTop) { printf("動態內存分配失敗\n"); exit(-1); } else { pS->pBottom = pS->pTop; pS->pTop->pNext = NULL; } } void push(PSTACK pS, int val) { PNODE pNew = (PNODE)malloc(sizeof(NODE)); //創建新的節點 pNew->data = val; //將val的值賦給新節點的數據域 pNew->pNext = pS->pTop; //將新節點的指針域指向下一個節點.pS->Top不能改寫成pS->Bottom pS->pTop = pNew; //pTop指向新節點 return; } void traverse(PSTACK pS) { PNODE p = pS->pTop; while(p != pS->pBottom) { printf("%d ", p->data); p = p->pNext; } printf("\n"); return; } bool empty(PSTACK pS) { if(pS->pTop == pS->pBottom) { return true; } else { return false; } } bool pop(PSTACK pS,int * pVal) { if(empty(pS)) { return false; } else { PNODE r = pS->pTop; *pVal = r->data; pS->pTop = r->pNext; free(r); r = NULL; return true; } } //清空棧 void clear(PSTACK pS) { if(empty(pS)) //如果 { return; } else { PNODE p = pS->pTop; //定義元素p指向棧頂元素 PNODE q = NULL; //定義元素q,初始值為空 while(p !=pS->pBottom) //如果棧不為空 { q = p->pNext; //q指向p的下一個元素 free(p); //釋放p所指向的棧頂元素 p = q; //將q所指向的元素賦給p } pS->pTop = pS->pBottom; } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。