寒假集训营第三课:数据结构初级(栈)

一.栈的简介

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(&amp;stack);//---对栈修改需要取地址
	//对栈的访问是要付出代价的---根据栈的定义来证明
	StackPush(&amp;stack, 1);
	StackPush(&amp;stack, 2);
	StackPush(&amp;stack, 3);
	StackPush(&amp;stack, 4);
	//后进先出
	while (!StackEmpty(&amp;stack))
	{
		printf("%d ", StackTop(&amp;stack));
		StackPop(&amp;stack);
	}
	printf("\n");
	StackDestory(&amp;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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值