【数据结构】 模拟实现栈
引言:栈作为一种经典的数据结构,是一种只能在一端进行插入和删除操作的特殊线性表,在C++的STL中也提供其接口<stack>
,直接提供了对栈操作的所有函数,在平时许多撸代码应用场景下非常实用且便捷。
- 定义:栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
实现原理如图:
代码如下:
Stack.h
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<assert.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* _a;
int _top;//栈顶
int _capacity;//容量
}Stack;
void StackInit(Stack* ps);
void StackDestory(Stack* ps);
void StackPush(Stack* ps, STDataType x);
void StackPop(Stack* ps);
STDataType StackTop(Stack* ps);
int StackEmpty(Stack* ps);
int StackSize(Stack* ps);
void TestStack();
Stack.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
void StackInit(Stack* ps)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = 0;
ps->_top = 0;
}
void StackDestory(Stack* ps)
{
assert(ps);
if (ps->_a != NULL);
{
free(ps->_a);
ps->_capacity = 0;
ps->_top = 0;
ps->_a = NULL;
}
}
void StackPush(Stack* ps, STDataType x)
{
assert(ps);
if (ps->_top == ps->_capacity)
{
size_t newcapacity = ps->_capacity == 0 ? 2 : ps->_capacity * 2;
ps->_a = (STDataType*)realloc(ps->_a,newcapacity*sizeof(STDataType));
assert(ps->_a != NULL);
ps->_capacity = newcapacity;
}
ps->_a[ps->_top] = x;
ps->_top++;
}
void StackPop(Stack* ps)
{
assert(ps &&ps->_top>0);
--ps->_top;
}
STDataType StackTop(Stack* ps)
{
assert(ps);
return ps->_a[ps->_top - 1];
}
int StackEmpty(Stack* ps)
{
assert(ps);
return ps->_top == 0;
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}
void TestStack()
{
Stack s;
StackInit(&s);
StackPush(&s, 1);
StackPush(&s, 2);
StackPush(&s, 3);
StackPush(&s, 4);
while (!StackEmpty(&s))
{
printf("%d", StackTop(&s));
StackPop(&s);
}
printf("\n");
/*StackDestory(&s);*/
}
Test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
int main()
{
TestStack();
system("pause");
return 0;
}