链栈LinkStack源码:
#pragma once template <class T> class Node { public: T data; Node<T> *next; }; template <class T> class LinkStack { public: LinkStack(void) { top = NULL; } //入栈 void push(T obj) { Node<T> * newNode = new Node<T>(); newNode->data = obj; newNode->next = top; top=newNode; } //出栈 T pop() { if(!IsEmpty()) { T tempData = top->data; Node<T> * tempTop = top->next; delete (top); top = tempTop; return tempData; } } //判断栈是否为空 bool IsEmpty() { if(top == NULL) return true; else return false; } ~LinkStack(void) { } private: Node<T> * top; };
链栈测试代码:
LinkStack<int> *stack2 = new LinkStack<int>(); stack2->push(2);stack2->push(6);stack2->push(8);stack2->push(4); stack2->push(1);stack2->push(3);stack2->push(5);stack2->push(7); while(!stack2->IsEmpty()) { std::cout<<stack2->pop()<<" "; }