一.栈的简介
1.栈是类似于箱子堆的数据结构,可以往里面存放和取出数据;
2.栈的存储数据原则:先进后出:
3.只能对栈顶(最上面的数据)进行操作:
4.栈的两大元素:栈的大小和栈顶指针top。
二.栈的存储方式
顺序存储:顺序栈,即堆栈的顺序存储结构。利用一组地址连续的存储单元依次存放自栈底到栈顶的元素,同时使用指针 top 指示栈顶元素在顺序栈中的位置。
链式存储:链式栈,即堆栈的链式存储结构。利用单链表的方式来实现堆栈。栈中元素按照插入顺序依次插入到链表的第一个节点之前,并使用栈顶指针 top 指示栈顶元素, top 永远指向链表的头节点位置。
三.代码演示
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
//动态栈
typedef int StackType;
typedef struct Stack
{
int* a;
int top;//记录栈顶的位置
int capacity;//容量
}Stack;
//接口
void StackInit(Stack* ps);
void StackDestory(Stack* ps);
void StackPush(Stack* ps,int x);//栈顶插入
void StackPop(Stack* ps);//栈顶删除
bool StackEmpty(Stack* ps);//判断栈是否为空
int StackTop(Stack* ps);//取出栈顶元素
#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"
int main()
{
Stack stack;
StackInit(&stack);//---对栈修改需要取地址
//对栈的访问是要付出代价的---根据栈的定义来证明
StackPush(&stack, 1);
StackPush(&stack, 2);
StackPush(&stack, 3);
StackPush(&stack, 4);
//后进先出
while (!StackEmpty(&stack))
{
printf("%d ", StackTop(&stack));
StackPop(&stack);
}
printf("\n");
StackDestory(&stack);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"
//void StackInit(Stack* ps)
//{
// assert(ps);
// //将栈初始化为0;
// ps->a = NULL;
// ps->top = 0;
// ps->capacity = 0;
//}
//void StackDestory(Stack* ps)
//{
// assert(ps);
// free(ps->a);
// ps->a = NULL;
// ps->capacity = ps->top = 0;
//}
//void StackPush(Stack* ps, int x)//栈顶插入
//{
// //分两种情况
// //第1种是先放数据后++,此时top初始化为0;
// //第2种是先++后放数据,此时top初始化为-1;
// assert(ps);
// //是否扩容
// if (ps->capacity == ps->top)
// {
// int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
// ps->a = realloc(ps->a, newcapacity * sizeof(int));
// if (ps->a==NULL)
// {
// printf("扩容失败\n");
// return;
// }
// ps->capacity = newcapacity;
// }
// ps->a[ps->top++] = x;
//}
//void StackPop(Stack* ps)//栈顶删除
//{
// assert(ps);
// assert(ps->top > 0);//top代表最后一个元素的下一个位置
// --ps->top;//因为如果要插入元素的话,那个数据是会被覆盖的
//
//
//}
//bool StackEmpty(Stack* ps)//判断栈是否为空
//{
// assert(ps);
// /*if (ps->top > 0)
// {
// return false;
//
// }
// else
// {
// return t