来源:互联网 发布:oracle数据库最高权限 编辑:程序博客网 时间:2024/05/23 14:48
************************* seqStack.cpp *************************#include <iostream>#include <vector>template <typename T, int size = 30>class SeqStack{public:SeqStack(){vec.reserve(size); //reserve:容器预留空间,无元素对象}~SeqStack(){vec.clear(); //clear:清空向量中所有元素}void clear(){vec.clear();}bool isEmpty(){return vec.empty(); //empty:如果向量不包括元素返回true}void push(const T& el){vec.push_back(el); //push_back:将元素加入向量的最后}T pop(){T el = vec.back(); //back:返回向量最后一个元素,返回值T或者T&vec.pop_back(); //pop_back:弹出向量最后一个元素,返回值voidreturn el;}T& topEl(){return vec.back();}private:vector<T> vec;};
************************* linkStack.cpp *************************#include <iostream>#include <list>template <typename T>class LinkStack{public:LinkStack(){};~LinkStack(){lst.clear(); //clear:清空链表中所有元素}void clear(){lst.clear();}bool isEmpty(){return lst.empty(); //empty:如果链表不包括元素返回true}void push(const T& el){lst.push_back(el); //push_back:将元素加入链表的最后}T pop(){T el = lst.back(); //back:返回链表最后一个元素,返回值T或者T&lst.pop_back(); //pop_back:弹出链表最后一个元素,返回值voidreturn el;}T& topEl(){return lst.back();}private:list<T> lst;};
************************* listStack.h *************************#include <iostream>template <typename T>typedef struct StackNode{T value;StackNode *next;}node;template <typename T>class ListStack{public:ListStack();~ListStack();void clear();bool isEmpty();void push(const T& el);T pop();T topEl();private:node<T> *head, *tail; //head指向栈底,tail指向栈顶.注意:<T>!};************************* listStack.cpp *************************#include <iostream>#include "listStack.h"template <typename T>ListStack<T>::ListStack(){head = tail = NULL;}template <typename T>ListStack<T>::~ListStack(){clear();}template <typename T>void ListStack<T>::clear(){while(!isEmpty()){pop();}}template <typename T>bool ListStack<T>::isEmpty(){return (head == tail && head == NULL);}template <typename T>void ListStack<T>::push(const T& el){node<T> *pNew = new node<T>(); //注意使用模板<T>pNew->value = el;pNew->next = NULL;if(isEmpty()){head = tail = pNew;}else{tail->next = pNew;tail = pNew; //tail指向新元素}}template <typename T>T ListStack<T>::pop(){T el;node<T> *tmp;if(isEmpty){throw("Empty");}else{if(head == tail) //只有一个元素{tmp = tail;head = tail = NULL;}else{node<T> *pCur = head; //找到tail的前驱while(pCur->next != tail)pCur = pCur->next;tmp = tail;pCur->next = NULL;tail = pCur;}}el = tmp->value;delete tmp;return el;}template <typename T>T ListStack<T>::topEl(){return tail->value;}
************************* hanoiTower.cpp *************************#include <iostream>void move(char A, char B){printf("%c --> %c \n", A, B);}void hanoi(int n, char A, char B, char C){if( n <= 1 ){move( A, C );}else{hanoi( n-1, A, C, B );move( A, C );hanoi( n-1, B, A, C );}}


0 0
原创粉丝点击