0624,栈,队列(C语言实现)

目录

思维导图

01 栈的单链表实现:

解答:

答案:

02 队列的循环数组实现:

解答:

答案

01 栈的单链表实现:

用单链表实现栈

#include <stdbool.h>

typedef int E;

typedef struct node {
    E data;
    struct node* next;
} Node;

typedef struct {
    Node* top;
    int size;
} Stack;

// API
Stack* stack_create(void);
void stack_destroy(Stack* s);

void stack_push(Stack* s, E val);
E stack_pop(Stack* s);
E stack_peek(Stack* s);

bool stack_empty(Stack* s);

解答:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef int E;
typedef struct node {   //栈内部结点
    E data;
    struct node* next;
} Node;

typedef struct {        //栈
    Node* top;
    int size;
} Stack;


Stack* stack_create(void) {
    Stack* sta= malloc(sizeof(Stack));  //申请栈
    if (!sta) {
        printf("error in stack_create\n");
        exit(1);
    }
    //更新栈信息
    sta->size = 0;
    sta->top = NULL;
    return sta;
}
void stack_destroy(Stack* s) {
    free(s->top);
    free(s);
}

void stack_push(Stack* s, E val) {
    //新建结点,赋值
    Node* newnode = malloc(sizeof(Node));
    if (!newnode) {
        printf("error in stack_push\n");
        exit(1);
    }
    newnode->data = val;
    newnode->next = s->top;    
    //更新栈信息
    s->top = newnode;
    s->size++;
}
E stack_pop(Stack* s) {  //头删除
    //记录top->next
    //删除top,free
    //new_top 
    Node* newtop = s->top->next;
    E del = s->top->data;
    free(s->top);
    s->top = newtop;
    //更新栈信息
    s->size--;
    return del;
}
E stack_peek(Stack* s) {   //查看栈顶元素
    return s->top->data;
}

bool stack_empty(Stack* s) {
    if (s->size) {
        return false;
    }
    return true;
}



int main(void) {
    Stack* s = stack_create
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值