使用链表实现的队列,先进先初,压入弹出判空。
1 // 基于链表的队列 2 #include <iostream> 3 using namespace std; 4 template <typename T> 5 class Queue 6 { 7 public: 8 //在构造过程中初始化为空队列 9 Queue(void) : m_rear (NULL), m_front (NULL) {} 10 //在析构过程中销毁剩余节点 11 ~Queue(void) 12 { 13 for (Node* next; m_front; m_front = next) 14 { 15 next = m_front->m_next; 16 delete m_front; 17 } 18 } 19 // 压入 20 void push(T data) 21 { 22 Node* node = new Node(data); 23 if (m_rear) 24 m_rear->m_next = node; 25 else 26 m_front = node; 27 m_rear = node; 28 } 29 // 弹出 30 T pop(void) 31 { 32 if (empty()) 33 throw UnderFlow(); 34 T data = m_front->m_data; 35 Node* next = m_front->m_next; 36 delete m_front; 37 if (!(m_front = next)) 38 m_rear = NULL; 39 return data; 40 } 41 // 判空 42 bool empty(void) 43 { 44 return !m_front && !m_rear; 45 } 46 private: 47 //下溢异常 48 class UnderFlow : public exception 49 { 50 const char* what(void) const throw () 51 { 52 return "队列下溢"; 53 } 54 }; 55 //节点 56 class Node 57 { 58 public: 59 Node(T data, Node* next = NULL) : 60 m_data (data), m_next (next) {} 61 T m_data; //数据 62 Node* m_next; //后指针 63 }; 64 Node* m_rear; 65 Node* m_front; 66 }; 67 68 // 测试基本类型 69 void test_int(void) 70 { 71 Queue<int> queue; 72 for (int i = 0; i < 5; ++i) 73 queue.push(i); 74 while (!queue.empty()) 75 cout << queue.pop() << endl; 76 cout << endl; 77 } 78 79 // 测试类 80 struct List 81 { 82 List(string name, int price) : m_name (name), 83 m_price (price) {} 84 string m_name; 85 int m_price; 86 }; 87 void test_class(void) 88 { 89 List l1("小米", 1999); 90 List l2("iphone 5s", 5288); 91 Queue<List> queue; 92 queue.push(l1); 93 queue.push(l2); 94 // cout << queue.pop().m_name << queue.pop().m_price << endl; 95 // cout << queue.pop().m_price << queue.pop().m_name << endl; 96 List l = queue.pop(); 97 cout << l.m_name << "手机, 价格: " << l.m_price 98 << "元." << endl; 99 } 100 101 //测试string类 102 void test_string(void) 103 { 104 string s1 = "C"; 105 string s2 = "C++"; 106 string s3 = "c#"; 107 string s4 = "java"; 108 Queue<string> queue; 109 queue.push(s1); 110 queue.push(s3); 111 queue.push(s3); 112 queue.push(s4); 113 cout << queue.pop() << endl; 114 cout << queue.pop() << endl; 115 cout << queue.pop() << endl; 116 cout << queue.pop() << endl; 117 cout << queue.pop() << endl; 118 } 119 int main(void) 120 { 121 try 122 { 123 //test_int(); 124 //test_string(); 125 test_class(); 126 } 127 catch (exception& ex) 128 { 129 cout << ex.what() << endl; 130 return -1; 131 } 132 return 0; 133 }