数据结构-栈和队列

本文详细探讨了数据结构中的栈和队列,分别介绍了它们的特性:栈作为后进先出(LIFO)结构,主要用于模拟递归;队列则遵循先进先出(FIFO)原则,常实现为循环队列。文中还通过实例讲解了顺序栈和链式栈,以及顺序队列和链式队列的实现,并提供了相关源代码。
摘要由CSDN通过智能技术生成

栈(LIFO-last in Frist out)

仅在表尾(栈顶)进行插入删除操作的线性表.

表尾又叫栈顶(top),表头又叫栈底(base)

插入到栈顶叫入栈(push)

删除栈顶元素叫出栈(pop)

队列(FIFO-fist in Frist out)

仅在表尾插入,在表头删除操作的线性表

队列一般以循环队列出现这里也实现循环队列了,其实在任何语言中实现这些本身真没啥意义

插入(入队)删除(出队)

顺序栈

简单方便,但容易溢出(数组大小固定),容易造成溢出

sequence_stack.h

#pragma once
#include<iostream>

using namespace std;

const int MAX_SIZE = 100;

template<class T>
class SequenceStack
{
public:
	SequenceStack();			//初始化栈
	~SequenceStack();			//析构函数
	void destroy();				//销毁栈
	bool isEmpty();				//判空
	int size();					//元素个数
	T top();					//返回栈顶元素
	void clear();				//清空栈
	void push(const T& element);		//插入元素(栈顶,入栈)
	void pop();					//删除元素(栈顶,出栈)
private:
	T* m_top;					//栈顶指针
	T* m_base;					//栈底指针
	int m_size;					//栈中元素个数
};

template<class T>
inline SequenceStack<T>::SequenceStack()
{
	this->m_base = new T[MAX_SIZE];
	if (!m_base)
	{
		cout << "new overflow" << endl;
		exit(1);
	}

	this->m_top = this->m_base;
	this->m_size = MAX_SIZE;
}

template<class T>
inline SequenceStack<T>::~SequenceStack()
{
	if (this->m_base)
	{
		delete[] this->m_base;
		this->m_base = nullptr;
		this->m_top = nullptr;
		this->m_size = 0;
	}
}

template<class T>
inline void SequenceStack<T>::destroy()
{
	if (this->m_base)
	{
		delete[] this->m_base;
		this->m_base = nullptr;
		this->m_top = nullptr;
		this->m_size = 0;
	}
}

template<class T>
inline bool SequenceStack<T>::isEmpty()
{
	if (this->m_base == this->m_top)
	{
		return true;
	}

	return false;
}

template<class T>
inline int SequenceStack<T>::size()
{
	return this->m_top - this->m_base;
}

template<class T>
inline T SequenceStack<T>::top()
{
	// TODO: 在此处插入 return 语句
	return *this->m_top;
}

template<class T>
inline void SequenceStack<T>::clear()
{
	this->m_top = this->m_base;
}

template<class T>
inline void SequenceStack<T>::push(const T& element)
{
	if (this->m_top - this->m_base == MAX_SIZE)
	{
		cout << "push overflow" << endl;
		return;
	}

	*++m_top = element;
}

template<class T>
inline void SequenceStack<T>::pop()
{
	if (this->m_top == this->m_base)
	{
		
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值