用两种方法实现栈---顺序表和链表

本文介绍了栈这种先进后出的数据结构,并提供了使用顺序表和链表两种方式实现栈的代码示例,包括push、pop、size、top和empty等基本操作。
摘要由CSDN通过智能技术生成

栈是一种先进后出的数据结构,栈中的数据是先进后出的(First In Last Out, FILO)。栈只有一个出口,允许新增元素(只能在栈顶上增加)、移出元素(只能移出栈顶元素)、取得栈顶元素等操作。在STL中,栈是以别的容器作为底部结构,再将接口改变,使之符合栈的特性就可以了。栈里面常用的函数有push()(增),pop()(删),size()(求大小),top()(顶部)和empty()(空),

下面是用顺序表实现栈的各种函数

顺序表代码实现:

#include <iostream>
#include <assert.h>
using namespace std;


template<typename T>
class Stack
{
public:
	Stack()
		:_a(NULL)
		, _top(0)
		, _capacity(0)
	{}

	~Stack()
	{
		if (_a)
		{
			delete[] _a;
		}
	}

public:

	void _CheckCapacity()
	{
		if (_a == NULL)
		{
			_capacity = 3;
			_a = new T[_capacity];
			return;
		}

		if (_top == _capacity)
		{
			_capacity *= 2;
			T* tmp = new T[_capacity];
			for (size_t i = 0; i < _top; i++)
			{
				tmp[i] = _a[i];
			}

			delete[] _a;
			_a = tmp;
		}

	}

	void Push(const T& x)
	{
		_CheckCapacity();
		_a[_top++] = x;
	}

	void Pop()
	{
		assert(_top > 0);
		--_top;
	}

	size_t Size()
	{
		return _top;
	}

	bool Empty()
	{
		return _top == 0;
	}

	T& Top()
	{
		return _a[_top];
	}


	
private:
	T* _a;
	size_t _top;
	size_t _capacity;
};

链表实现栈:

链表实现代码:

#include <iostream>
#include <assert.h>
using namespace std;

template<typename T>
struct Node
{
	Node(const T& x)
		:_data(x)
		,_next(NULL)
	{}

	T _data;
	Node<T>* _next;
};

template<typename T>
class Stack
{
public:
	Stack()
		:_top(NULL)
		,_base(NULL)
		,_size(0)
	{}

	~Stack()
	{}

	void Push(const T& x)
	{
		if (_top == NULL)
		{
			_top = new Node<T>(x);
			_base = _top;
		}
		else
		{
			
			_top->_next = new Node<T>(x);
			_top = _top->_next;
		}
		++_size;
	}

	void Pop()
	{
		assert(_top);
		
		Node<T>* cur = _base;
		
		while (cur->_next != _top)
		{
			if (cur == NULL)
			{
				printf("Stack is empty!\n");
				return;
			}
			cur = cur->_next;
		}

		delete _top;
		_top = cur;
		--_size;
	}

	T& Top()
	{
		return _top->_data;
	}
	bool Empty()
	{
		return _top == NULL;
	}
	size_t Size()
	{
		return _size;
	}


private:
	Node<T>* _top;
	Node<T>* _base;
	size_t _size;
};


测试代码:

test.cpp

void Test()
{
	Stack<int> s1;
	s1.Push(0);
	s1.Push(1);
	s1.Push(2);
	s1.Push(3);
	s1.Push(4);
	s1.Push(5);

	s1.Pop();
	s1.Pop();
	s1.Pop();

	int top = s1.Top();
	size_t size = s1.Size();
	cout << s1.Empty() << endl;


}

int main()
{
	Test();
	system("pause");
	return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值