栈的基本操作(链栈 顺序栈)

栈在数据结构中扮演重要角色,尽管不复杂,但能有效解决复杂问题。栈可以逻辑上表现为链式或顺序结构,通过数组或指针实现。本文将介绍面向对象的链栈和顺序栈源码实现。

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

栈作为数据结构很重要的一部分 不是很难 但是对于解决很多复杂问题有责非常重要的作用 栈的逻辑结构可以是顺序或者链序的 相对应的是数组实现和指针实现 在这里分别给出相应的源码,博主采用的是面向对象实现。

1.链栈

#include <iostream>
using namespace std;
class node{
	public:
	int data;
	node* next;
};
class stack  //该栈为带头结点的链栈 
{
	public:
		stack();
		~stack();
		bool empty();
		void pushstack(int );
		void popstack();
		void gettop();
		void printstack();
	private:
		node* top;
	protected:
};
stack::stack()
{
	top->next=NULL;
}
stack::~stack()//析构函数 删除链栈
{
	node* p=new node;
	node* q=top->next;
	while(q){
		p=q;
		q=q->next;
		delete p;
	}
}
bool stack::empty()//判空
{
	if(top->next==NULL)
		return true;
	return false;
}
void stack::gettop()//打印栈顶元素
{
	if(empty())
		cout<<"empty stack"<<endl;
	cout<<"top element is "<<top->next->data<<endl;
}
void stack::pushstack(int a)//压栈
{
	node* p=new node;
	p->data=a;
	p->next=top->next;
	top->next=p;
}
void stack::popstack()  //弹栈
{
	if(empty())
		cout<<"empty stack!"<<endl;
	node* q=top->next;
	top->next=q->next;	
}	
void stack::printstack()
{
	node* p=top->next;
	while(p){
		cout<<p->data;
		p=p->next;
	}
}
	
int main(int argc, char** argv) {
	stack A;
	int num;
	cin>>num;
	while(num!=-1)     //键盘输入数据 -1为终止符
	{
		A.pushstack(num);
		cin>>num;
	}
	A.printstack();   //打印栈中元素
	return 0;
}	

2.顺序栈
用数组实现

#define maxsize 100
#include <iostream>
using namespace std;
class stack
{
public:
	stack();
	~stack();
	void pushstack(int) ;
	void popstack();
	bool is_empty();
	bool is_full();
	int gettop();
	void printstack();
private:
	int top;
	int data[maxsize];
};
bool stack::is_empty()
{
	if(top == -1)
		return true;
	return false;
}
bool stack::is_full()
{
	if(top == maxsize-1)
		return true;
	return false;
}
void stack::pushstack(int a)
{
	if(is_full()){
		cout<<"full stack!"<<endl;
		return;
		}		
	data[++top]=a;
}
void stack::popstack()
{
	if(is_empty()){
		cout<<"empty stack!"<<endl;
		return;
	}
	top--;
}
int stack::gettop()
{
	if(is_empty())
		return -1; //栈为空返回-1
	return data[top]; 
}
void stack::printstack()
{
	if(is_empty()){
		cout<<"empty stack!"<<endl;
		return;	
	}
	for(int i=top;i>=0;){
		cout<<data[top--];
	}
}
int main()
{
	stack A;
	int num;
	cin>>num;
	while(num != -1){
		A.pushstack(num);
		cin>>num;
	}
	A.printstack();
	return 1;
	 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值