顺序栈的C实现

测试文件:

#include <stdio.h>
#include "seq_stack.h"

int main()
{
    int array[] = {3,2,1,4,5,6,7};
    pstack ps = init_stack();
    ps = create_stack(array, 7);
    // int i;
    // for(i=0; i<7; i++)
    //     push(ps, array[i]);
    display_stack(ps);
    ps = push(ps, 8);
    ps = push(ps, 9);
    pop(ps);
    display_stack(ps);
    return 0;
}

实现文件

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "seq_stack.h"

#define TRUE        0
#define FALSE       1
#define MAX_SIZE    1024

pstack init_stack()
{
    int i;
    pstack ps;
    if((ps = (pstack)malloc(sizeof(s_stack))) == NULL){
        printf("Init sequence stack error\n");
        return NULL;
    }
    ps->top = -1;
    ps->array = (Element *)malloc(sizeof(Element));    
    return ps;
}

pstack create_stack(Element *arr, int len)
{
    if(len > MAX_SIZE){
        printf("Wrong array length");
        return NULL;
    }
    int i;
    pstack ps = init_stack();
    for(i=0; i<len; i++)
    {
        ps->array[i] = arr[i];
        ps->top++;
    }
    return ps;
}

int is_empty(pstack ps)
{
    return ((ps->top == -1)?TRUE : FALSE);
}

int is_full(pstack ps)
{
    return ((ps->top == MAX_SIZE)?TRUE : FALSE);
}

Element get_top(pstack ps)
{
    if(is_empty(ps) == 0)
    {
        printf("Sequence stack is empty\n");
        return 0;
    }
    else
        return ps->array[ps->top];
}

Element pop(pstack ps)
{
    if(is_empty(ps) == 0)
        return 0;
    ps->top--;
    return ps->array[ps->top+1];   
}

pstack push(pstack ps, Element e)
{
    if(is_full(ps) == 0)
    {
        printf("Sequence stack is full\n");
        return ps;  
    }
    ps->top++;
    ps->array[ps->top] = e;    
    return ps;
}

void display_stack(pstack ps)
{
    int t = ps->top;
    if(is_empty(ps) == 0)
        printf("Sequence stack is empty\n");
    else
    {
        while(t != -1)
        {
            printf("%d ", ps->array[t]);
            t--;
        }
        printf("\n");
    }
}

头文件:

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef int Element;
// top points to the top node of the stack
typedef struct s_stack
{
    int top;
    Element* array;
}s_stack, *pstack;

pstack init_stack();

pstack create_stack(int *arr, int len);

int is_empty(pstack ps);
int is_full(pstack ps);
Element get_top(pstack ps);
Element pop(pstack ps);
pstack push(pstack ps, Element e);
void display_stack(pstack ps);

typedef struct l_stack
{
    int top;
}l_stack;
#endif // STACK_H_INCLUDED



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值