栈线性表的实现方式 seqstack.h 和 seqstack.c

seqstack.h 文件

#ifndef _SEQ_STACK_H_
#define _SEQ_STACK_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//用线性表的顺序存储模拟栈的顺序存储,在尾部插入删除元素不会涉及大量元素移动
typedef void Stack;

#ifndef bool
#define bool int
#define true 1
#define false 0
#endif

Stack* SeqStack_Create(int capacity);
bool SeqStack_Destory(Stack* stack);
bool SeqStack_Clear(Stack* stack);
bool SepStack_Push(Stack* stack, void* item);
void* SeqStack_Pop(Stack* stack);
void* SeqStack_Top(Stack* stack);
int SeqStack_GetSize(Stack* stack);
int SeqStack_GetCapacity(Stack* stack);
#endif

seqstack.c 文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "seqlist.h"
#include "seqstack.h"

//利用线性表的存储结构模拟线性栈

//创建栈相当于创建线性表
Stack* SeqStack_Create(int capacity)
{

    return SeqList_Create(capacity);

}

bool SeqStack_Destory(Stack* stack)
{
    return SeqList_Destroy(stack);
}

bool SeqStack_Clear(Stack* stack)
{
    return SeqList_Clear(stack);
}

//向栈中插入元素相当于向线性表的尾部插入元素
bool SepStack_Push(Stack* stack, void* item)
{
    return SeqList_InsertOneNode(stack,item,SeqList_GetLength(stack));//线性表尾部插入元素
}

//栈弹出元素相当于从线性表的尾部取元素,注意弹出来了
void* SeqStack_Pop(Stack* stack)
{

    return SeqList_DeleteOneNode(stack,SeqList_GetLength(stack) - 1);

}
//获取栈顶的元素相当于从读取线性表的尾部元素,没有弹出来
void* SeqStack_Top(Stack* stack)
{

    return SeqList_GetOneNode(stack,SeqList_GetLength(stack) - 1);

}
//获取栈的大小相当于获得线性表的实际长度
int SeqStack_GetSize(Stack* stack)
{
    return SeqList_GetLength((List*)stack);
}
//获取栈的容量相当于获取线性表的容量
int SeqStack_GetCapacity(Stack* stack)
{
    return SeqList_GetCapacity((List*)stack);
}


/****************************测试代码*********************/

/*
void main()
{
    int i = 0;
    //定义一个数组之后一定给他赋值,否则数组元素是编译器默认分配的,不一定是0,很难办
    int aa[10] = {0};
    Stack* stack = NULL;
    stack = SeqStack_Create(10);
    if (stack == NULL)
    {
        printf("创建stack失败");
    }

    for (i = 0; i < 5; i ++)
    {
        aa[i] = aa[i] + i +1; 
        SepStack_Push(stack,&aa[i]);
    }

    printf("栈的容量:%d\n",SeqStack_GetCapacity(stack));
    printf("栈的大小:%d\n",SeqStack_GetSize(stack));
    printf("栈顶元素:%d\n", *((int*)SeqStack_Top(stack)));

    while (SeqStack_GetSize(stack) > 0)
    {
        printf("栈以次弹出元素:%d\n",*((int*)SeqStack_Pop(stack)));
    }
    SeqStack_Destory(stack);
    system("pause");
}
*/

上述可能会调用其它头文件或源文件,如果遇到,请翻看我的其它博客,对其头文件和源文件的实现方式。
good luck!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值