作者:小 琛
欢迎转载,请标明出处
栈的概念及结构
栈一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据也在栈顶。
栈的实现
栈的代码实现有两种方法:通过数组和通过链表。而结合对栈性能——出入栈仅仅在栈顶。我们选择数组法,因为链表的尾插和尾删代价相对较大。
Stack.h
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef int Datetype;
typedef struct Stack
{
Datetype* _a;
size_t top;
size_t capacity;
}Stack;
void StackInit(Stack* pst);
void StackDestroy(Stack* pst);
void StackPush(Stack* pst, Datetype Date);
void StackPop(Stack* pst);
Datetype StackTop(Stack* pst);
size_t StackSize(Stack* pst);
int StackEmpty(Stack* pst);
Stack.c
#include "Stack.h"
/*
函数功能:栈的初始化
*/
void StackInit(Stack* pst)
{
assert(pst);
pst->_a = NULL;
pst->top = pst->capacity = 0;
}
/*
函数功能:栈的销毁
*/
void StackDestroy(Stack* pst)
{
assert(pst);
free(pst->_a);
pst->_a = NULL;
pst->top = pst->capacity = 0;
}
/*
函数功能:入栈
*/
void StackPush(Stack* pst,Datetype Date)
{
assert(pst);
if (pst->top == pst->capacity)
{
Datetype newcapacity = pst->capacity == 0 ? 4 : pst->capacity* 2;
pst->_a = (Datetype*)realloc(pst->_a, newcapacity);
}
pst->_a[pst->top] = Date;
pst->top++;
}
/*
函数功能:出栈
*/
void StackPop(Stack* pst)
{
assert(pst&&pst->top > 0);
pst->top--;
}
/*
函数功能:获取栈的顶端数据
*/
Datetype StackTop(Stack* pst)
{
assert(pst);
return pst->_a[pst->top - 1];
}
/*
函数功能:获取目前的总数据量
*/
size_t StackSize(Stack* pst)
{
assert(pst);
return pst->top;
}
/*
函数功能:判断栈是否为空,返回1为空
*/
int StackEmpty(Stack* pst)
{
assert(pst);
return pst->top == 0 ? 1 : 0;
}
text.c
#include "Stack.h"
void text()
{
Stack stack;
StackInit(&stack);
StackPush(&stack, 1);
StackPush(&stack, 2);
StackPush(&stack, 3);
StackPush(&stack, 4);
StackPush(&stack, 5);
while (StackEmpty(&stack) == 0)
{
printf("%-4d", StackTop(&stack));
StackPop(&stack);
}
}
int main()
{
text();
return 0;
}
结果如下:
可以看到,先入栈的先出栈,后入栈的后出栈。