数组、链表实现栈(C语言版)

//数组实现栈
#include <stdio.h>

#define STACK_SIZE 50

typedef struct SeqStack
{
    int data[STACK_SIZE];
    int top;
}stack;

void InitStack()
{
    s->top = -1;
}

int IsFull(stack *s)
{
    return (s->top == STACK_SIZE - 1);
}

int IsEmpty(stack *s)
{
    return (s->top == -1);
}

void Push(stack *s,int n)
{
    if(IsFull(s))
    {
        printf("Stack is full!\n");
        return;
    }
    s->top++;
    s->data[s->top] = n;
}

int Pop(stack *s)
{
    if(IsEmpty(s))
    {
        printf("Stack is empty!\n");
        return -1;
    }
    return s->data[s->top--];
}

void main()
{
    stack *s = (stack *)malloc(sizeof(stack));
    if(s == NULL)
    {
        printf("Malloc failed!");
        exit(-1);
    }

    InitStack(s);

    int i;
    for(i=0;i<10;i++)
    {
        Push(s,i);
    }

    while(!IsEmpty(s))
    {
        int data = Pop(s);
        printf("%d->",data);
    }
}


//链表实现栈
#include<stdio.h>

typedef struct LinkListNode
{
    int data;
    struct LinkListNode *next;
}node;

typedef struct LinkStack
{
    node *top;
}stack;

void init_stack(stack *s)
{
    s->top = NULL;
}

void push_stack(stack *s,int data)
{
    node *newnode=(node *)malloc(sizeof(node));
    newnode->data=data;
    newnode->next=s->top;
    s->top=newnode;
}

int pop_stack(stack *s)
{
    int temp;
    node *p;
    if(s->top==NULL)
    {
        printf("stack is empty,can't pop stack\n");
        return -1;
    }
    temp=s->top->data;
    p=s->top;
    s->top=s->top->next;
    free(p);
    return temp;
}

int main()
{
    stack *s=(Stack*)malloc(sizeof(stack));
    init_stack(s);

    int i;
    for(i=0;i<10;i++)
    {
        push_stack(s,i);
    }

    for(i=0;i<10;i++)
    {
        printf("%d\n",pop_stack(s));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值