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");
}