栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构06-栈

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构06-栈

栈和队列是两种我们应用非常广的数据机构,这两个都是线性表的一种,今天我们主要来谈谈栈。
栈的主要代码:

#include
using namespace std;
#define MaxSize 10

//初始化,压栈,入栈
typedef struct Stack {
	int top;
	int data[MaxSize];
}Stack;

Stack* Stack_Init()
{
	Stack* temp = new Stack;
	if (!temp)
	{
		cout << "申请内存失败" << endl;
		return NULL;
	}
	temp->top = -1;
	return temp;
}

void PrintStack(Stack* temp)
{
	int index = temp->top;
	while (index>= 0)
	{
		cout << temp->data[index] << " ";
		index--;
	}
	cout << endl;
}

void push(Stack* temp,int data)
{
	if (temp->top + 1 == MaxSize)
	{
		cout << "栈满" << endl;
		return;
	}
	temp->data[++temp->top] = data;
}

int pop(Stack* temp)
{
	if (temp->top < 0)
	{
		cout << "栈空" << endl;
		return -1;
	}
	temp->top--;
	return temp->data[temp->top + 1];
}

void Stacktest()
{
	Stack* temp = Stack_Init();
	push(temp, 10);
	push(temp, 11);
	push(temp, 12);
	push(temp, 13);
	push(temp, 14);
	PrintStack(temp);
	pop(temp);
	pop(temp);
	PrintStack(temp);
}
int main()
{
	Stacktest();
	return 0;
}

我们知道,栈是一种先进后出(FILO)的数据结构,如此以来,我们的操作只涉及到栈顶元素,所以我们需要一个指向栈顶元素的指针——top(这里我们使用的数组下标)。正因为我们只涉及到栈顶元素,所以栈的操作只有两个:压栈和出栈。压栈——顾名思义,就是把元素压入栈中(栈中空间足够的情况下)。所以我们只需要将新数据记录到栈中,并且将指向栈顶元素的指针指向新纳入的元素即可。至于出栈,由于我的栈是由数组作为基本元素构造而成的,所以此时我们只需要将top指针往下移动一位就可以了,如果是指针实现的,还需要释放之前的栈顶元素。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/873170.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号