数据结构——线性表:顺序栈,链式栈(C++)

内容概要:

  • 栈的基本概念及注意事项
  • 顺序栈、链式栈的C++模板类的实现

栈的基本概念及注意事项:

  • 栈(stack)是限定仅在一端进行插入或删除操作的线性表。
  • 与顺序表和链表一样,栈分为顺序栈和链式栈。
  • 栈顶(top)元素、入栈(push)、出栈(pop)

       图示:

       

       

       

  • 栈广泛应用于递归中,使用栈可以模拟递归。

实现代码(测试环境VS2017):

//Stack_ADT.h

#ifndef STACK_ADT_H
#define STACK_ADT_H

template<typename E>
class Stack
{
private:
	void operator =(const Stack&){}
	Stack(const Stack&){}

public:
	Stack(){}
	virtual ~Stack(){}

	virtual void clear() = 0;
	virtual void push(const E&it) = 0;
	virtual E pop() = 0;
	virtual const E& topValue() const = 0;
	virtual int length() const = 0;
};

#endif // !STACK_ADT_H
//array_based_stack.h

#ifndef ARRAY_BASED_STACK_H
#define ARRAY_BASED_STACK_H

#include<assert.h>
#include"Stack_ADT.h"

template<typename E>
class AStack :public Stack<E>
{
private:
	int maxSize;
	int top;
	E*listArray;

public:
	AStack(int size = 100)//default size 100
	{
		maxSize = size;
		top = 0;
		listArray = new E[size];
	}
	~AStack() { delete[]listArray; }

	void clear() { top = 0; }
	void push(const E& it)
	{
		assert(top != maxSize);//stack is full
		listArray[top++] = it;
	}
	E pop()
	{
		assert(top != 0);//stack is empty
		return listArray[--top];
	}
	const E& topValue() const
	{
		assert(top != 0);//stack is empty
		return listArray[top - 1];
	}
	int length() const{ return top; }
};

#endif // !ARRAY_BASED_STACK_H
//linked_stack.h

#ifndef LINKED_STACK_H
#define LINKED_STACK_H

#include"Stack_ADT.h"

template<typename E>
class SLink
{
public:
	E element;
	SLink*next;

	//两个构造函数
	SLink(const E&elemval, SLink*nextval = NULL){ element = elemval; next = nextval; }
	SLink(SLink*nextval = NULL) { next = nextval; }
};

template<typename E>
class LStack :public Stack<E>
{
private:
	SLink<E>*top;
	int size;

public:
	LStack(int s = 100)//default size 100, no use
	{
		top = NULL;
		size = 0;
	}
	~LStack() { clear(); }

	void clear()
	{
		while (top != NULL)
		{
			SLink<E>*temp = top;
			top = top->next;
			delete temp;
		}
		size = 0;
	}
	void push(const E&it)
	{
		top = new SLink<E>(it, top);
		size++;
	}
	E pop()
	{
		assert(top != NULL);//stack is empty
		E it = top->element;
		SLink<E>*ltemp = top->next;
		delete top;
		top = ltemp;
		size--;
		return it;
	}
	const E& topValue() const
	{
		assert(top != NULL);//stack is empty
		return top->element;
	}
	int length() const { return size; }
};

#endif // !LINKED_STACK_H
//《数据结构与算法分析(第三版)P76-P81》
//main.cpp

#include<iostream>
#include"array_based_stack.h"
#include"linked_stack.h"
using namespace std;

int main()
{
	
	//test place

	system("pause");
}

转载请注明出处:https://blog.csdn.net/Hodge_Z/article/details/85063143

猜你喜欢

转载自blog.csdn.net/Hodge_Z/article/details/85063143