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

数据结构学习笔记(C++):栈的链式存储结构

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

数据结构学习笔记(C++):栈的链式存储结构

本程序主要体现了线性表的链式存储结构,主要实现了以下几个功能:

//压栈

//出栈

//取栈顶

//判断栈是否为空

下面是代码,如有不足的地方还请各位大佬多多指正:

//数据结构学习笔记(C++):栈的链式存储结构 
#include
using namespace std;

class linkStack{	 
public:
	struct Node
	{
		int data;
		Node *next;
	};
	
public:
	linkStack();//构造函数
	~linkStack();//析构函数

public:
	void Push(int x);//压栈	
	int Pop();//弹栈
	int getTop();//取栈顶
	bool isEmpty();//判空函数

private:
	Node *top;//栈帧 
};
//1
linkStack::linkStack()//构造函数
{
	//因为链栈是不具有头节点的,所以直接让栈帧为空即可
	top = NULL; 
}
//2
linkStack::~linkStack()//析构函数
{
	Node* p = NULL;//定义工作指针 
	while(top!=NULL)
	{
		p = top;
		top = top->next;
		delete p;
	}
}
//3
void linkStack::Push(int x)//压栈操作
{
	Node *s = NULL;
	s = new Node;
	s->data = x;
	s->next = top;
	top = s;
}
//4
int linkStack::Pop()//弹栈操作
{
	Node *p = NULL;
	int x;
	if(top == NULL) throw "下溢";
	x = top->data;
	p = top;
	top = top->next;
	delete p;
	return x;
}
//5
int linkStack::getTop()//取栈顶 
{
	return top->data;
}
//6
bool linkStack::isEmpty()//判断栈是否为空
{
	if(top == NULL)
		return true;
	else
		return false;
} 

int main()
{
	linkStack stack;
	char command;
	int x;
	try{
		while(cin>>command)
		{
			if(command == 'Q')
				return 0;
			switch(command)
			{
				case 'P'://压栈 
					cout<<"输入要压入的元素";
					cin>>x;
					stack.Push(x);
					cout<<"压栈完成。"< 

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

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

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