算法复习(5)链表实现的堆栈

  复习算法的时候,实然想用链表实现堆栈。就着手去写,顺便复习一下STL的内容。C++涉及的内容太多,折腾完VC及MFC,再回头,好像又不会了。

今天是第一次贴完整的代码呢,不知道会不会有大神看到给指正指正。

 1 //基于链式表的堆栈
  2 #include <iostream>
  3 using namespace std;
  4 class Student
  5 {
  6 public:
  7     int m_no;
  8     string m_name;
  9     int m_age;
 10     
 11     Student(int no, const string& name, int age) :
 12         m_no (no), m_name (name), m_age (age) {}
 13     void show(void) 
 14     {   
 15         cout << m_name << "同学: 学号" << m_no << ", 年龄"
 16             << m_age << "岁." << endl;
 17     }   
 18 };
 19 
 20 template <typename T>
 21 class Stack
 22 {
 23 private:
 24     //下溢异常
 25     class UnderFlow : public exception
 26     {   
 27         const char* what(void) const throw()
 28         {
 29             return "堆栈下溢!";
 30         }
 31     };
 32     //节点
 33     class Node {
 34     public:
 35         T m_data;     //数据
 36         Node* m_next;   //后指针
 37         Node(T data, Node* next = NULL) :
 38             m_data (data), m_next (next) {}
 39     };
 40     Node* m_top;    //栈顶
 41 public:
 42     //构造过程中初始化为空堆栈
 43     Stack(void) : m_top (NULL) {}
 44     //析构过程中释放剩余节点
 45     ~Stack(void)
 46     {
 47         for (Node* next; m_top; m_top = next)
 48         {
 49             next = m_top->m_next;   //先备份m_top,好访问后节点
 50             delete m_top;
 51         }
 52    }
 53     //压入
 54     void push(T data)
 55     {
 56         m_top = new Node (data, m_top);
 57     }
 58     //弹出
 59     T pop(void)
 60     {
 61         if (empty())
 62             throw UnderFlow();
 63         T data = m_top->m_data;
 64         Node* next = m_top->m_next;
 65         delete m_top;
 66         m_top = next;
 67         return data;
 68     }
 69     //判空
 70     bool empty(void)
 71     {
 72         return !m_top;
 73     }
 74 };
 75 void test_string(void)
 76 {
 77         //测试string类型
 78         Stack<string> stack;
 79         stack.push("hello");
 80         stack.push("world");
 81         cout << stack.pop() << endl;
 82         cout << stack.pop() << endl;
 83 }
 84 void test_class(void)
 85 {
 86         //测试自定义类类型
 87         Stack<Student> stack;
 88         Student stu1(1, "张飞", 33);
 89         Student stu2(2, "刘备", 40);
 90         stack.push(stu1);
 91         stack.push(stu2);
 92 
 93         stack.pop();
 94         stack.pop();
 95         Student stu =stack.pop();
 96         stu.show();
 97 }
 98 int main(void)
 99 {
100     try
101     {
102         test_string();
103         test_class();
104     }
105     catch (exception& ex)
106     {
107         cout << ex.what() << endl;
108         return -1;
109     }
110     return 0;
111 }
View Code
原文地址:https://www.cnblogs.com/itit/p/3442481.html