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順序設計有所協助。