C說話對棧的完成根本操作。本站提示廣大學習愛好者:(C說話對棧的完成根本操作)文章只能為提供參考,不一定能成為您想要的結果。以下是C說話對棧的完成根本操作正文
c說話中棧是一種數據構造,落後先出,即最初進入棧的數據最早彈出。c說話中沒有棧這類數據類型,須要本身編程構建。上面我們就一路來懂得一下c說話中棧的根本操作。
C說話對棧的完成根本操作,操作以下:
#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; } }
願望本文所述對年夜家c法式設計有所贊助。