顺序栈和链栈的实现

定义:

	是限定仅在表尾进行插入或删除操作的线性表。对栈来说,表尾端称为栈顶,表头端称为栈底,不含元素的空表称为空栈。栈是LIFO的(LAST IN FIRST OUT 后进先出)

操作:

	栈的基本操作除了在栈顶进行插入或删除外,还有栈的初始化、判空及取栈顶元素等。

实现:

	实现栈的方式有两种,一种以连续内存实现,即顺序栈。一种采用链式存储结构实现的栈,即内存不连续的。
	下面提供这两种栈的C++实现

顺序栈: SequenceStack

#pragma once
enum StackStatus
{
	ERROR=0,
	OK=1,
};
const int MaxSize = 100;
template 
class SequenceStack
{
	/**
	 * 顺序栈的C++实现
	 * @author  wzx
	 * @data    2019年3月4日
	 */

	/*
	 * 顺序栈可以申请连续内存的方式可以通过申请动态数组或者直接使用STL中vector容器实现
	 * 此处采用申请动态数组的方式。缺点即当栈中元素超过所定义的容量时将不会入栈。
	 * 注意:此处的模板T类型默认支持赋值运算符或者重写了复制构造函数和赋值运算符
	 */
private:
	T* base;
	T *top;
	
public:
	SequenceStack();
	~SequenceStack();
	void ClearStack();
	bool IsStackEmpty();
	int StackLength();
	StackStatus GetTop(T &t);
	StackStatus Push(T t);
	StackStatus Pop(T &t);
};

template 
SequenceStack::SequenceStack()
{
	base = new T[MaxSize];
	if (!base)
	{
		throw "内存申请异常!";
	}
	top = base;
}

template 
SequenceStack::~SequenceStack()
{
	delete[]base;
}
template 
void SequenceStack::ClearStack()
{
	if (top != base)
	{
		top = base;
	}
}
template 
bool SequenceStack::IsStackEmpty()
{
	return top == base;
}
template 
int SequenceStack::StackLength()
{
	return top-base;
}

template 
StackStatus SequenceStack::GetTop(T &t)
{
	if (top == base)
		return ERROR;
	else
	{
		t = *(top-1);
		return OK;
	}
}

template 
StackStatus SequenceStack::Pop(T &t)
{
	if (top == base)
	{
		return ERROR;
	}
	else
	{
		t = *(--top);
		return OK;
	}
}
template 
StackStatus SequenceStack::Push(T t)
{
	if (top - base >= MaxSize)
		return ERROR;
	else
	{
		*(top++) = t;
		return OK;
	}
}

链栈 :ListStack

#pragma once

enum StackStatus
{
	ERROR = 0,
	OK = 1,
};
template
struct StackNode
{
	T data;
	StackNode *next;
};
template
class ListStack
{
	/**
	 * 链栈的C++实现
	 * @author  wzx
	 * @data    2019年3月4日
	 */
private:
	StackNode *pStack;
	int currentSize;
public:
	ListStack();
	~ListStack();
	int size();
	StackStatus Pop(Type &t);
	StackStatus Push(Type t);
	StackStatus getTop(Type &t);
	bool isStackEmpty();
};

template
ListStack::ListStack()
{
	pStack = 0;
	currentSize = 0;
}

template
ListStack::~ListStack()
{
	if (pStack != 0)
	{
		StackNode *p = 0;
		while (pStack)
		{
			p = pStack;
			pStack = pStack->next;
			delete p;
		}
	}
}
template
int ListStack::size()
{
	return currentSize;
}

template
StackStatus ListStack::Pop(Type &t)
{
	if (pStack == 0)
		return ERROR;
	else
	{
		t = pStack->data;
		StackNode *p = pStack;
		pStack = pStack->next;
		delete p;
		--currentSize;
		return OK;
	}
}

template
StackStatus ListStack::Push(Type t)
{
	StackNode* p = 0;
	p = new StackNode;
	p->data = t;
	p->next = pStack;
	pStack = p;
	++currentSize;
	return OK;
}
template
StackStatus ListStack::getTop(Type &t)
{
	if (!pStack)
		return ERROR;
	else
	{
		t = pStack->data;
		return OK;
	}
}

template
bool ListStack::isStackEmpty()
{
	if (pStack)
		return false;
	else
		return true;
}

你可能感兴趣的:(数据结构和基础算法,顺序栈和链栈的实现,数据结构)