数据结构———栈的基本实现

本文介绍了栈这种后进先出的数据结构,并提供了C++的实现,包括初始化、入栈、出栈、获取栈顶元素、判断栈是否为空、获取栈内元素数量和销毁栈等操作。此外,还展示了使用栈进行交互式操作的测试代码,特别提到了栈在二叉树遍历和图的深度优先遍历中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



一、栈是什么?

是一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端为栈顶,另一端为栈底。栈中元素遵循先进后出的原则
假设我们依次将1, 2, 3, 4压入栈中
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

二、具体实现

废话不多说,来,上代码!

1.stack.h

#include <iostream>
#include <sperror.h>
#include <cassert>

using namespace std;

typedef int Type;

struct Stack
{
	Type* a;
	int top;
	int capacity;
};

void Init_stack(Stack* s);

void Push_back(Stack* s, Type x);

void Pop(Stack* s);

Type get_top(Stack* s);

int stack_size(Stack* s);

bool is__empty(Stack* s);

void stack_Destroy(Stack* s);

2.stack.cpp

代码如下(示例):

#include "Stack.h"

void Init_stack(Stack* s)
{
	s->capacity = 5;
	s->top = 0;
	s->a = (Type*)malloc(sizeof(Type) * s->capacity);
}

void check(Stack* s)
{
	if (s->capacity == s->top)
	{
		int newcapacity = s->capacity * 2;
		Type* tmp = (Type*)realloc(s->a, sizeof(Type) * newcapacity);
		if (tmp != NULL)
		{
			s->a = tmp;
			s->capacity = newcapacity;
		}
		else
			perror("realloc:");
	}
}

void Push_back(Stack* s, Type x)
{
	check(s);
	s->a[s->top] = x;
	s->top++;
}

bool is__empty(Stack* s)
{
	if (s->top <= 0)
		return true;
	else
		return false;
}

void Pop(Stack* s)
{
	assert(!is__empty(s));
	s->top--;
}

Type get_top(Stack* s)
{
	assert(!is__empty(s));
	return s->a[s->top-1];
}

int stack_size(Stack* s)
{
	return s->top;
}

void stack_Destroy(Stack* s)
{
	s->a = NULL;
	s->capacity = 0;
	s->top = 0;
	s = NULL;
}

3.test.cpp

#include "Stack.h"

void menu()
{
	cout << "---------------------------------------------" << endl;
	cout << "----1.入栈-----------------2.出栈------------" << endl;
	cout << "----3.获得栈顶-------------4.判空------------" << endl;
	cout << "----5.获取栈内元素长度-----6.销毁栈----------" << endl;
	cout << "---------------------------------------------" << endl;
}

enum function
{
	Exit,
	push_back,
	pop,
	get_topval,
	isempty,
	get_size,
	destroy
};

void test()
{
	Stack s;
	Init_stack(&s);
	int choice = 0;
	do {
		menu();
		cin >> choice;
		switch (choice)
		{
		case push_back:
			int x;
			cout << "输入要入栈的元素:";
			cin >> x;
			Push_back(&s, x);
			break;

		case pop:
			Pop(&s);
			break;

		case get_topval:
			cout << get_top(&s) << endl;
			break;

		case isempty:
			if (is__empty(&s))
				cout << "Yes" << endl;
			else
				cout << "No" << endl;
			break;

		case get_size:
			cout << stack_size(&s) << endl;
			break;

		case destroy:
			stack_Destroy(&s);
			break;

		case Exit:
			cout << "退出!" << endl;

		}

	} while (choice);
}
int main()
{
	test();
}

总结

栈是一种后进先出的数据结构,由于作者水平和经验不多,目前直到的具体应用场景为二叉树的遍历和图的深度优先遍历方面,随着以后学习的深入,我会进一步补充和修改这方面。

评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值