C++实现顺序栈和链栈

一,栈的相关概念

1,栈的定义和特点

在这里插入图片描述

在这里插入图片描述

2,入栈和出栈

在这里插入图片描述
在这里插入图片描述

3,栈的应用

在这里插入图片描述

二,顺序栈的实现

#include<iostream>
using namespace std;
#define MaxSize 100

template<typename T>
class Stack
{
    
    
	public:
		Stack();		
		bool IsEmpty();		
		int GetLength();
		int Clear();
		void Push(T x);
		void Pop();
		~Stack();
	private:
		int top;
		T *list;
};

template<typename T>
Stack<T>::Stack() //栈的初始化 
{
    
    
	top = 0;
	list = new T[MaxSize];
}

template<typename T>
bool Stack<T>::IsEmpty() //判断栈是否为空 
{
    
    
	return top==0?1:0;
}
	
template<typename T>
int Stack<T>::GetLength()   //获得栈中数据元素的个数
{
    
    
	return top;
}	
	
template<typename T>
int Stack<T>::Clear()  //清空栈 
{
    
    
	top = 0;
}
	
template<typename T>
void Stack<T>::Push(T x)  //入栈 
{
    
    
	if(top==MaxSize)
	{
    
    
		cout << "栈已满";
		return;
	}
	else
	{
    
    
		list[top] = x;
		top++;
	}
}
	
template<typename T>
void Stack<T>::Pop() //出栈 
{
    
    
	if(top==0)
	{
    
    
		cout << "栈为空";
	}
	else
	{
    
    
		top--;
	}
}

template<typename T>
Stack<T>::~Stack() //销毁栈 
{
    
    
	if(list)
	{
    
    
		delete[] list;
		list = NULL;
	}
} 

int main()
{
    
    
	
}

三,链栈的实现

#include<iostream>
using namespace std;

template<typename T>
struct node  //栈中存储的元素 
{
    
    
	T data; //元素的数据域 
	node* next; //指向下一个元素的指针 
};

template<typename T>
class Stack
{
    
    	
	public:
		Stack();
		bool IsEmpty();
		T GetTop();
		void Push(const T a);
		void Pop();
		int GetLength();
		~Stack();
	private:
		node<T>* top;
		int count;
};

template<typename T>
Stack<T>::Stack() //链栈初始化 
{
    
    
	top = NULL;
	count = 0;
}

template<typename T>
Stack<T>::~Stack() //链栈销毁 
{
    
    
	while(!IsEmpty())
	{
    
    
		Pop();
	}
}

template<typename T>
bool Stack<T>::IsEmpty() //判断链栈是否为空 
{
    
    
	return count == 0;
}

template<typename T>
T Stack<T>::GetTop() //获得栈顶元素 
{
    
    
	if(!IsEmpty())
	{
    
    
		return top->data;
	}
	else
	return 0;
}

template<typename T>
void Stack<T>::Push(const T a) //入栈 
{
    
    
	node<T>* s = new node<T>();
	s->data = a;
	s->next = top;
	top = s;
	count++;
}

template<typename T>
void Stack<T>::Pop() //出栈 
{
    
    
	if(IsEmpty())
	{
    
    
		cout << "栈为空";
	}
	else
	{
    
    
		node<T>* u = top;
		top = top->next;
		delete u;
		count--;
	}
}

template<typename T>
int Stack<T>::GetLength() //获得栈中元素个数 
{
    
    
	return count;
}

int main()
{
    
    
	Stack<int> lists;
	for(int i=1; i<6; i++)
	{
    
    
		lists.Push(i);
	}
	for(int i=0; i<3; i++)
	{
    
    
		lists.Pop();
	}
	lists.Push(6);
	lists.Push(7);
	lists.Pop();
	int size = lists.GetLength();
	for(int i=0; i<size; i++)
	{
    
    
		cout << lists.GetTop() << " ";
		lists.Pop();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_46027243/article/details/113810014