C++重写Stack类

基于STL模板库及侯捷的源码剖析。全部代码都已经过测试检验。

头文件1:node.h

#ifndef _NODE_H_
#define _NODE_H_
#include <iostream>
using namespace std;

//栈元素类
template <class T>
class node
{
public:
	node<T>* next;  
	T val;  
	node() :next(NULL), val() {};   //默认构造入栈节点
	node(T v) :next(NULL), val(v) {};   //构造入栈节点
};

#endif // _NODE_H

头文件2:Stack.h

#ifndef _STACK_H_
#define _STACK_H_
#include "node.h"

//栈模板类
template <class T>
class Stack
{
private:
	node<T>* top;
	size_t len;
public:
	Stack();
	~Stack();
	bool is_empty();  //判断栈是否为空
	size_t get_len();  //返回入栈元素个数
	T* get_top();   //返回指向栈顶元素的指针
	void push(const T& e);  //入栈
	T pop();     //出栈
	void display();  //打印栈元素
};

//构造空栈
template <class T>
Stack<T>::Stack()
{
	top = NULL;
	len = 0;
	cout << "栈已建立" << endl;
}

//析构
template <class T>
Stack<T>::~Stack()
{
	node<T>* pre = top;
	if (top)
	{
		delete top;
		top = pre->next;
		pre = pre->next;
	}
	len = 0;
}

//判断栈是否为空
template <class T>
bool Stack<T>::is_empty()
{
	return len == 0;
}

//返回入栈元素个数
template <class T>
size_t Stack<T>::get_len()
{
	return len;
}

//返回指向栈顶元素的指针
template <class T>
T* Stack<T>::get_top()
{
	return top;
}

//入栈
template <class T>
void Stack<T>::push(const T& e)
{
	node<T>* tmp = new node<T>(e);
	if (top == NULL)
	{
		top = tmp;
	}
	else 
	{
		tmp->next = top;
		top = tmp;
	}
	++len;
}

//出栈
template <class T>
T Stack<T>::pop()
{
	T ret;
	if (is_empty())
		throw new exception("The stack is empty!");
	if (len == 1)
	{
		ret = top->val;
		top = NULL;
	}
	else
	{
		ret = top->val;
		node<T>* tmp = top;
		top = top->next;
		delete tmp;
	}
	--len;
	return ret;
}

//打印栈元素
template <class T>
void Stack<T>::display()
{
	node<T>* pre = top;
	cout << "The stack is :";
	while (pre) 
	{
		cout << pre->val << " ";
		pre = pre->next;
	}
	cout << endl;
}

#endif // _STACK_H

测试文件:demo.cpp

#include "Stack.h"

int main()
{
    Stack<int> s;
    int x;
    cout << "请输入入栈元素:" << endl;
    while (cin>>x)  s.push(x);
    s.display();
    cout << "弹出栈顶元素:" << s.pop() << endl;
	cout << "弹出栈顶元素后:" << endl;
	s.display();
    cout << "栈元素个数:" << s.get_len() << endl;

    system("pause");
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LiuZuqiang_3027

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值