C++实现栈(顺序栈和链栈)

//栈
//规则:1、先进后出 2、只能访问栈顶元素 3、只能在栈顶进行元素的插入或删除
//存储方式分为顺序存储和链式存储

//栈的顺序存储(用数组模拟)
//数组的开头为栈底,末尾为栈顶,方便元素的插入和删除
#include<iostream>
using namespace std;

class Stack{
private:
	int *arr;
	int top; //指向栈顶位置元素
	int size; //栈的大小
public:
	Stack(int s);
	void push(int n);
	int pop();
	~Stack();
	bool Is_empty();
};
 
//初始化
Stack::Stack(int s){
	this->arr = new int[s];
	this->size = s;
	this->top = -1;
	cout<<"初始化完成"<<endl;
}

//析构
Stack::~Stack(){
	if(this->arr!=nullptr)
		delete[] arr;
	cout<<"析构成功"<<endl;
}

//入栈
void Stack::push(int n){
	if(this->top<this->size-1){
		this->top+=1;
		this->arr[top] = n;
		cout<<"入栈成功"<<endl;
		return;
	}
	cout<<"入栈失败"<<endl;
	return;
}

//出栈
int Stack::pop(){
	if(this->arr==nullptr || this->top==-1){
		cout<<"出栈失败"<<endl;
		return -1;
	}
	else{
		int num = this->arr[this->top];
		top-=1;
		return num;
	}
}

//判空
bool Stack::Is_empty(){
	if(this->arr==nullptr)
	{	
		cout<<"栈指针为空"<<endl;
		return false;
	}
	else if(this->top==-1)
		return true;
	else
		return false;
}

int main(){
	Stack s(5);
	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);
	s.push(5);
	s.push(6); //这个会失败,因为超出了空间

	while(!s.Is_empty()){
		cout<<s.pop()<<endl;
	}
}


//链栈
//链表头为栈顶,方便插入删除,链表尾作为栈底
#include<iostream>
using namespace std;

class Node{
public:
	Node *next;
	int data;
};

class Stack{
private:
	Node *top; //指向栈顶节点,注意栈顶节点相当于链表头节点,不存储数据,只是为了操作方便
	int size;  //链栈含有节点个数
public:
	Stack();
	~Stack();
	void push(int data);
	int pop();
	bool Is_empty();
	void myprint();
};

Stack::Stack(){
	top = new Node;
	top->data = -1;
	top->next = nullptr;
	size = 0;
	cout<<"初始化成功"<<endl;
}

Stack::~Stack(){
	Node *p = top;
	while(size>0){
		p = p->next;
		delete top;
		top = p;
		size-=1;
	}
	cout<<"析构成功"<<endl;
}

void Stack::push(int data){
	Node *n = new Node;
	n->data = data;
	n->next = top->next;
	top->next = n;
	size+=1;
	cout<<"插入成功"<<endl;
}

int Stack::pop(){
	Node *n = new Node;
	n = top->next;
	top->next = n->next;

	int temp = n->data;
	size-=1;
	delete n;
	return temp;
}

bool Stack::Is_empty(){
	if(size==0 || top==nullptr){
		cout<<"栈空"<<endl;
		return true;
	}
	else{
		cout<<"栈非空"<<endl;
		return false;
	}
}

void Stack::myprint(){
	if(size==0 || top==nullptr){
		cout<<"栈空"<<endl;
		return;
	}
	Node *p = top->next;
	while(p!=nullptr){
		cout<<p->data<<" ";
		p = p->next;
	}
	cout<<endl;
}

int main(){
	Stack s;
	s.Is_empty();

	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);
	s.Is_empty();

	cout<<s.pop()<<endl;
	cout<<s.pop()<<endl;
	s.myprint();
	s.Is_empty();
}

猜你喜欢

转载自blog.csdn.net/qq_43438974/article/details/129380347