文章目录
- 一、什么是栈
- 二、栈的实现
- 三、实现栈所需的函数
- 四、完整栈的展现
- 五、栈的思维导图
一、什么是栈
栈是一种特殊的线性表,只允许在固定的一端进行插入和删除操作。进行插入和删除的一段叫做栈顶,另一段叫做栈底
压栈:插入数据
出栈:删除数据
压栈和出栈都是在栈顶
二、栈的实现
栈的实现分为两种方式,用数组或者链表实现,相较于链表而言,数组实现尾插的代价更小,所以我们用数组实现
三、实现栈所需的函数
- 1.栈的初始化
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
- 2.栈的销毁
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
- 3.栈的插入
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType)*newcapacity);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
插入的时候我们首先要考虑容量是否够,这里与top比较一下,如果刚好相等,我们可以realloc二倍扩容,扩容好了之后top就要+!
- 4.栈元素的删除
void StackPop(ST* ps)
{
assert(ps);
assert(ps->a);
ps->top--;
}
这里直接让top-1,下次如果想要插入的话直接可以把之前top元素覆盖
- 5.取栈顶元素
STDataType StackTop(ST* ps)
{
assert(ps);
assert(ps->a);
return ps->a[ps->top - 1];
}
- 6.栈中元素的个数
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
- 7.栈元素是否为空的判断
bool StackEmpty(ST* ps)
{
return ps->top==0;
}
四、完整栈的展现
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int QDataType;
typedef struct QueueNode
{
int val;
struct QueueNode* next;
}QueueNode;
typedef struct Queue
{
QueueNode* phead;
QueueNode* ptail;
int size;
}Queue;
void QueueInit(Queue* pq);
void QueueDestroy(Queue* pq);
void QueuePush(Queue* pq, QDataType x);
void QueuePop(Queue* pq);
QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
bool QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);
#define _CRT_SECURE_NO_WARNINGS 1
#include"stack.h"
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = ps->top = 0;
}
void StackPush(ST* ps, STDataType x)
{
assert(ps);
if (ps->capacity == ps->top)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType)*newcapacity);
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(ps->a);
ps->top--;
}
STDataType StackTop(ST* ps)
{
assert(ps);
assert(ps->a);
return ps->a[ps->top - 1];
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool StackEmpty(ST* ps)
{
return ps->top==0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include"stack.h"
int main()
{
ST p;
StackInit(&p);
StackPush(&p, 1);
StackPush(&p, 2);
StackPush(&p, 3);
StackPush(&p, 4);
StackPush(&p, 5);
StackPush(&p, 6);
StackPush(&p, 7);
while (!StackEmpty(&p))
{
printf("%d ", StackTop(&p));
StackPop(&p);
}
return 0;
}