C语言链栈与顺序栈的实现

C语言链栈与顺序栈的实现

顺序栈

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 10
typedef int DataType;
typedef struct {
    DataType buf[MAX];
    DataType top;

}SeqStack;
SeqStack *create_empty_stack(){
    SeqStack *stack = NULL;
    stack = (SeqStack *)malloc(sizeof(SeqStack));
    if(stack == NULL){
        printf("faild to malloc");
        return NULL;
    }
    memset(stack,0,sizeof(stack));
    return stack;
}
void init_seqstack(SeqStack *stack){
    stack->top = 0;
}
int is_empty(SeqStack *stack){
    if(stack->top = -1){
        return 0;
    }
    return 1;
}
void push(SeqStack *stack,DataType data){
    
    stack->buf[stack->top] = data;
    stack->top++;
}
void pop(SeqStack *stack){
    stack->top--;
}
int main(int argc, char const *argv[])
{
    SeqStack *p = create_empty_stack();
    push(p,1);
    push(p,2);
    push(p,3);
    pop(p);
    return 0;
}

链栈

要注意的是push的时候需要传入二级指针top

#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct node
{
    DataType data;
    struct node *next;

} LinkStack;
LinkStack *create_empty_linkstack()
{
    LinkStack *top = NULL;
    top = (LinkStack *)malloc(sizeof(LinkStack));
    if (top == NULL)
    {
        printf("faild to malloc LinkStack\n");
        return NULL;
    }
    top->next = NULL;
    return top;
}
int is_empty(LinkStack *top)
{
    if(top->next == NULL){
        printf("linkstack is empty\n");
    }
    return top->next == NULL ? 0 : 1;
}
LinkStack *push(LinkStack **top, DataType data)
{
    LinkStack *newnode = NULL;
    newnode = (LinkStack *)malloc(sizeof(LinkStack));
    if (newnode == NULL)
    {
        printf("faild to malloc LinkStack\n");
    }
    newnode->data = data;
    newnode->next = *top;
    *top = newnode;
    //return top;
}
void pop(LinkStack *top){
    if(!is_empty(top)){
        printf("linkstack is empty\n");
        exit(EXIT_FAILURE);
    }
    top = top->next;
}
int getTop(LinkStack *top){
    is_empty(top);
    return top->data;
    
}
int main(int argc, char const *argv[])
{
    LinkStack *top = create_empty_linkstack();
    
    push(&top,2);
    push(&top,8);
    push(&top,6);
    is_empty(top);
    printf("top value:%d\n",getTop(top));
    return 0;
}

输出结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值