目录
一、什么是栈
栈(Stack)是一种数据结构,它遵循先进后出(LIFO)的原则。这意味着最后进入栈的元素会被最先移出。栈通常比较适合用于需要后进先出顺序访问元素的场景,比如函数调用、表达式求值、括号匹配等。
栈有两个基本操作:
- 入栈(Push):将元素压入栈顶。
- 出栈(Pop):从栈顶移出元素。
通常栈还会支持其他操作,比如:
- 栈顶元素访问(Top):获取栈顶元素的值,但不移除它。
- 判空(isEmpty):检查栈是否为空。
- 获取栈的大小(Size):获取栈中元素的数量。
二、如何实现栈
数组和链表都可以用来实现栈,它们各自有一些优势和劣势,选择哪种实现方式取决于具体的需求和应用场景。
数组实现栈:
- 优势:
- 访问元素速度快,可以直接通过索引访问元素。
- 内存连续,空间利用率高。
- 劣势:
- 插入和删除操作的时间复杂度为 O(n),因为在数组中插入或删除元素可能需要移动其他元素。
- 当栈的大小不确定时,可能会造成内存浪费或需要频繁的扩容和缩容操作。
- 优势:
链表实现栈:
- 优势:
- 插入和删除操作的时间复杂度为 O(1),因为链表中插入或删除元素只需要修改指针,不需要移动其他元素。
- 可以动态地分配内存,无需提前指定栈的大小。
- 劣势:
- 访问元素的时间复杂度为 O(n),需要遍历链表到达目标元素。
- 链表节点需要额外的指针空间。
- 优势:
因此,如果对于栈的主要操作是压入和弹出元素,并且栈的大小不会频繁变化,那么使用数组实现栈可能更合适。但如果栈的大小不确定,或者频繁执行插入和删除操作,那么使用链表实现栈可能更为适用。
三、栈的C语言实现
采用数组实现栈,其实现方式类似于顺序表的实现。
关于顺序表请见博主的另一篇博客:http://t.csdnimg.cn/GBkSQ
3.1 stack.h
#pragma once
#include<stdbool.h>
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a; //数组
int top; //栈顶元素
int capacity; //数据个数
}ST;
//初始化
void STInit(ST* pst);
//销毁
void STDestroy(ST* pst);
//入栈
void STPush(ST* pst, STDataType x);
//出栈
void STPop(ST* pst);
//获取栈顶元素
STDataType STTop(ST* pst);
//判空
bool STEmpty(ST* pst);
//获取数据个数
int STSize(ST* pst);
3.2 stack.c
#include "stack.h"
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->capacity = 0;
//top指向栈顶元素的下一个位置
pst->top = 0;
top指向栈顶元素的位置
//pst->top = -1;
}
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = pst->top = 0;
}
void STPush(ST* pst, STDataType x)
{
assert(pst);
//扩容
if (pst->top == pst->capacity)
{
int newcapacity = 0;
if (pst->capacity == 0)
{
newcapacity = 4;
}
else
{
newcapacity = pst->capacity * 2;
}
STDataType* temp = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType));
if (temp == NULL)
{
perror("malloc");
exit(1);
}
pst->a = temp;
pst->capacity = newcapacity;
}
pst->a[pst->top] = x;
pst->top++;
}
void STPop(ST* pst)
{
assert(pst);
assert(pst > 0);
pst->top--;
}
STDataType STTop(ST* pst)
{
assert(pst);
assert(pst>0);
return pst->a[pst->top-1];
}
bool STEmpty(ST* pst)
{
assert(pst);
if (pst->top == 0)
{
return true;
}
else
{
return false;
}
}
int STSize(ST* pst)
{
assert(pst);
return pst->top;
}