您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)怎么用C語言實(shí)現(xiàn)鏈?zhǔn)綏5膬?nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
堆棧是只能在一端增刪元素的表結(jié)構(gòu),該位置稱為棧頂堆棧的基本運(yùn)算是壓入和彈出,前者相當(dāng)于插入,而后者則是刪除最后插入的元素,形成后進(jìn)先出的運(yùn)算規(guī)則最后插入的元素在被彈出之前可以作為棧頂被外界訪問從空棧中彈出,或向滿棧中壓入,都被認(rèn)為是一種錯(cuò)誤
順序棧
#include <stdio.h> #include <stdlib.h> /*節(jié)點(diǎn)的結(jié)構(gòu)*/ typedef struct node { struct node* pnode; int data; }node_t; /*棧的結(jié)構(gòu)*/ typedef struct stack { struct node* top;//棧頂指針 int size;//棧中數(shù)據(jù)個(gè)數(shù) }stack_t; /*初始化棧*/ void stack_init(stack_t* stk) { stk->top = NULL; stk->size = 0; } /*壓棧操作*/ void stack_push(stack_t* stk, int data) { node_t *node = malloc(sizeof(node_t)); node->data = data; node->pnode = stk->top; stk->top = node; stk->size++; } /*彈棧:將棧中數(shù)據(jù)彈入buf*/ void stack_pop(stack_t* stk, int buf[], int size) { for(int i = 0; i < size; ++i) { if(stk->size == 0) { printf("棧中數(shù)據(jù)已彈凈!\n"); break; } node_t* temp = stk->top; buf[i] = stk->top->data; stk->top = stk->top->pnode; stk->size--; free(temp); } } /*刪除整個(gè)棧*/ void stack_deinit(stack_t* stk) { while(stk->size || stk->top) { node_t* temp = stk->top; stk->top = stk->top->pnode; stk->size--; free(temp); } } /*從棧頂自上而下打印棧中所有數(shù)據(jù)*/ void print_stack(stack_t* stk) { if(stk->size == 0) { printf("棧中無數(shù)據(jù)!\n"); } for(node_t* node = stk->top; node; node = node->pnode) { printf("%d ",node->data); } printf("\n"); } /*測試代碼*/ #define N 30 int main(void) { stack_t stack; int buf[N]; stack_init(&stack); printf("開始?jí)簵?!\n"); for(int i = 0; i < N; ++i) { stack_push(&stack, i); } print_stack(&stack);//打印棧中數(shù)據(jù) //stack_deinit(&stack); printf("開始彈棧!\n"); stack_pop(&stack, buf, N);//彈棧 print_stack(&stack); printf("取出的數(shù)據(jù)為:"); for(int i = 0; i < sizeof(buf) / sizeof(buf[0]); ++i) { printf("%d ", buf[i]); } printf("\n"); return 0; }
感謝各位的閱讀!關(guān)于“怎么用C語言實(shí)現(xiàn)鏈?zhǔn)綏!边@篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。