栈:先进后出
这里以头插法创建链表形式作为栈的结构,最后插入的元素始终为链表头,而出栈时将删除链表头以实现先进后出,后进先出的特性
关于其应用值得一提的便是后缀表达式
/***********************************************
> Filename: Stack.cpp
> Author: Pyt
> Create: 2017-08-19 13:41:43
************************************************/
#include <iostream>
using namespace std;
template<typename T>
class Stack{
public:
Stack();
~Stack();
Stack(const Stack &t);
Stack& operator=(const Stack &t);
void push(const T &t);
void pop();
bool empty() const;
const T& top() const;
void clear();
private:
struct Node{
Node *next;
T val;
Node(T x) : val(x), next(NULL){}
};
Node *head;
int cursize;
};
template<typename T>
Stack<T>::Stack()
: cursize(0), head(NULL)
{
}
template<typename T>
Stack<T>::~Stack()
{
clear();
}
template<typename T>
Stack<T>::Stack(const Stack &t)
: cursize(t.cursize)
{
Node *pre = NULL;
Node *obj = t.head;
if(obj)
{
Node *tmp = new Node(obj->val);
pre = head = tmp;
obj = obj->next;
}
else{
head = NULL;
}
while(obj)
{
Node *tmp = new Node(obj->val);
pre->next = tmp;
pre = tmp;
obj = obj->next;
}
}
template<typename T>
Stack<T>& Stack<T>::operator=(const Stack &t)
{
if(this != &t)
{
Stack<T> tmp(t);
swap(head, tmp.head);
cursize = tmp.cursize;
}
return *this;
}
template<typename T>
void Stack<T>::push(const T& t)
{
if(head == NULL)
{
head = new Node(t);
}
else{
Node *tmp = head;
head = new Node(t);
head->next = tmp;
}
cursize++;
}
template<typename T>
void Stack<T>::pop()
{
if(!empty())
{
Node *tmp = head;
head = head->next;
delete tmp;
cursize--;
}
}
template<typename T>
bool Stack<T>::empty() const
{
return cursize == 0;
}
template<typename T>
const T& Stack<T>::top() const
{
if(!empty())
return head->val;
}
template<typename T>
void Stack<T>::clear()
{
while(head)
{
Node *tmp = head;
head = head->next;
delete tmp;
}
head = NULL;
cursize = 0;
}
int main()
{
Stack<int> a;
for(int i=0; i<10; i++)
a.push(i);
Stack<int> b(a);
b.pop();
cout << b.top() << " " << a.top() << endl;
while(!a.empty())
{
cout << a.top() << endl;
a.pop();
}
Stack<int> c;
c = b;
c.clear();
cout << c.empty() << endl;
return 0;
}