日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

用C語言實(shí)現(xiàn)鏈?zhǔn)綏=榻B_C 語言

作者:weixin_43361320 ? 更新時(shí)間: 2022-03-08 編程語言

堆棧的基本概念

堆棧是只能在一端增刪元素的表結(jié)構(gòu),該位置稱為棧頂堆棧的基本運(yùn)算是壓入和彈出,前者相當(dāng)于插入,而后者則是刪除最后插入的元素,形成后進(jìn)先出的運(yùn)算規(guī)則最后插入的元素在被彈出之前可以作為棧頂被外界訪問從空棧中彈出,或向滿棧中壓入,都被認(rèn)為是一種錯(cuò)誤

常見的棧有順序棧和鏈?zhǔn)綏?/strong>

順序棧

在這里插入圖片描述

鏈?zhǔn)綏?/p>

在這里插入圖片描述

- 鏈?zhǔn)綏5腃代碼實(shí)現(xiàn)

#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");
}

/*測(cè)試代碼*/
#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;
}

代碼運(yùn)行效果

在這里插入圖片描述

原文鏈接:https://blog.csdn.net/weixin_43361320/article/details/122030719