c++实现简单顺序栈与链栈

c++实现简单顺序栈与链栈

栈作为数据结构线性结构的一部分,栈的实现相对来说比较简便。本质上,顺序栈是顺序表的子集,链栈是链表的子集。在我看来,栈的实现无非是在类中留出更少的接口:只有尾插,尾删,获取top等几种。其稍稍与表的不同是栈是先进后出。即通过一个游动的top指针(顺序栈中用int top来表示数组中的成员位置)来进行对栈的操作。而表中无论是头指针还是尾指针都不动。下面给出实现代码,顺序依次为:顺序栈,链栈和测试。

SeqStack.hpp

#include <iostream>
using namespace std;
const int StackSize=1024;
template <class T>
class SeqStack
{
public:
	SeqStack() { this->top = -1; };
	void Push(T data);
	void Pop();
	T GetTop();
	bool IsEmpty() { return top == -1 ? true : false; };
	void StackPrint();
private:
	T arr[StackSize];
	int top;
};

template <class T>
void SeqStack<T>::Push(T data)
{
	if (top >= StackSize - 1)
	{
		cout << "栈已满" << endl;
	}
	else
	{
		top++;
		this->arr[top]=data;
	}
	return;
}

template <class T>
void SeqStack<T>::Pop()
{
	if (top == -1)
	{
		cout << "栈空" << endl;
	}
	else
	{
		top--;
	}
}

template <class T>
T SeqStack<T>::GetTop()
{
	if (top == -1)
	{
		cout << "栈空" << endl;
		return -1;
	}
	else
	{
		return this->arr[top];
	}
}

template <class T>
void SeqStack<T>::StackPrint()
{
	int p = top;
	while (p!= -1&&p>=0)
	{
		cout << this->arr[p]<<" ";
		p--;
	}
	cout << endl;
}

LinkStack.hpp

#include <iostream>
using namespace std;

template <class T> 
class Node
{
public:
	T data;
	Node* next;
};

template <class T>
class LinkStack
{
public:
	LinkStack(){top = NULL;};
	~LinkStack()
	{
		Node<T>* p = top;
		while (p)
		{
			top = p;
			p = p->next;
			delete top;
		}
	};
	void Push(T data)
	{
		Node<T>* temp = new Node<T>;
		temp->data = data;
		temp->next = top;
		top = temp;
	}
	void Pop()
	{
		Node<T>* p = top;
		p = p->next;
		delete top;
		top = p;
	}
	void LSPrint()
	{
		Node<T>* p = top;
		while (p != NULL)
		{
			cout << p->data << " ";
			p = p->next;
		}
		cout << endl;
	}
	T GetTop()
	{
		if (top != NULL)
		{
			return top->data;
		}
		else
		{
			return -1;
		}
	}
	bool IsEmpty() { return (top == NULL) ? true : false; };
private:
	Node<T>* top;
};

栈测试.cpp

#include <iostream>
using namespace std;
#include "SeqStack.hpp"
#include "LinkStack.hpp"
int main()
{
	SeqStack<int> SS;
	SS.Push(1);
	SS.Push(2);
	SS.Push(3);
	SS.StackPrint();
	SS.Pop();
	SS.StackPrint();
	cout<<"getTop = "<<SS.GetTop()<<endl;

	LinkStack<int>LS;
	LS.Push(4); LS.Push(5); LS.Push(6);
	LS.LSPrint();
	LS.Pop();
	LS.LSPrint();
	cout << "getTop = " << LS.GetTop() << endl;
	system("pause");
	return 0;
}

测试结果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值