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

學無先后,達者為師

網站首頁 編程語言 正文

用C語言實現鏈式棧介紹_C 語言

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

堆棧的基本概念

堆棧是只能在一端增刪元素的表結構,該位置稱為棧頂堆棧的基本運算是壓入和彈出,前者相當于插入,而后者則是刪除最后插入的元素,形成后進先出的運算規則最后插入的元素在被彈出之前可以作為棧頂被外界訪問從空棧中彈出,或向滿棧中壓入,都被認為是一種錯誤

常見的棧有順序棧和鏈式棧

順序棧

在這里插入圖片描述

鏈式棧

在這里插入圖片描述

- 鏈式棧的C代碼實現

#include <stdio.h>
#include <stdlib.h>

/*節點的結構*/
typedef struct node {
    struct node* pnode;
    int data;
}node_t;
/*棧的結構*/
typedef struct stack {
    struct node* top;//棧頂指針
    int size;//棧中數據個數
}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++;
}
/*彈棧:將棧中數據彈入buf*/
void stack_pop(stack_t* stk, int buf[], int size)
{
    for(int i = 0; i < size; ++i) {
        if(stk->size == 0) {
            printf("棧中數據已彈凈!\n");
            break;
        }
        node_t* temp = stk->top;
        buf[i] = stk->top->data;
        stk->top = stk->top->pnode;
        stk->size--;
        free(temp);
    }   
}
/*刪除整個棧*/
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);
    }   
}
/*從棧頂自上而下打印棧中所有數據*/
void print_stack(stack_t* stk)
{   
    if(stk->size == 0) {
        printf("棧中無數據!\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("開始壓棧!\n");
    for(int i = 0; i < N; ++i) {
        stack_push(&stack, i);
    }
    print_stack(&stack);//打印棧中數據
    //stack_deinit(&stack);
    printf("開始彈棧!\n");
    stack_pop(&stack, buf, N);//彈棧
    print_stack(&stack);
    printf("取出的數據為:");
    for(int i = 0; i < sizeof(buf) /
        sizeof(buf[0]); ++i) {
        printf("%d ", buf[i]);
    }
    printf("\n");
    return 0;
}

代碼運行效果

在這里插入圖片描述

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

欄目分類
最近更新