C++数据结构学习之栈和队列

  在C++数据结构学习中,顺序表示的队列,必须预先分配空间,并且空间大小受限,使用起来限制比较多。而且,由于限定存取位置,顺序表示的随机存取的优点就没有了,所以,链式结构应该是***。

  栈的定义和实现

 
 
 
  1. #ifndef Stack_H  
  2. #define Stack_H   
  3. #include "List.h"  
  4.  
  5. template <class Type> class Stack : List //栈类定义  
  6. {  
  7.  public:  
  8.   void Push(Type value)  
  9.   {  
  10.    Insert(value);  
  11.   }  
  12.  
  13.  Type Pop()  
  14.  {  
  15.   Type p = *GetNext();  
  16.   RemoveAfter();  
  17.   return p;  
  18.  }  
  19.  
  20.  Type GetTop()  
  21.  {  
  22.   return *GetNext();  
  23.  }  
  24.  
  25.  List  ::MakeEmpty;  
  26.  List  ::IsEmpty;  
  27.  
  28. };  
  29.  
  30. #endif 

  队列的定义和实现

 
 
 
  1. #ifndef Queue_H  
  2. #define Queue_H  
  3. #include "List.h"  
  4.  
  5. template <class Type> class Queue : List //队列定义  
  6. {  
  7.  public:  
  8.   void EnQueue(const Type &value)  
  9.   {  
  10.    LastInsert(value);  
  11.   }  
  12.  
  13.  Type DeQueue()  
  14.  {   
  15.   Type p = *GetNext();  
  16.   RemoveAfter();  
  17.   IsEmpty();  
  18.   return p;  
  19.  }  
  20.  
  21.  Type GetFront()  
  22.  {  
  23.   return *GetNext();  
  24.  }  
  25.  
  26.  List  ::MakeEmpty;  
  27.  List  ::IsEmpty;  
  28.  
  29. };  
  30. #endif 

  测试程序

 
 
 
  1. #ifndef StackTest_H  
  2. #define StackTest_H  
  3. #include "Stack.h"  
  4.  
  5. void StackTest_int()  
  6. {  
  7.  cout << endl << "整型栈测试" << endl;  
  8.  cout << endl << "构造一个空栈" << endl;  
  9.  Stack<int> a;  
  10.  cout << "将1~20入栈,然后再出栈" << endl;  
  11.  for (int i = 1; i <= 20; i++) a.Push(i);  
  12.   while (!a.IsEmpty()) cout << a.Pop() << ' ';  
  13.   cout << endl;  
  14. }  
  15. #endif  
  16.  
  17. #ifndef QueueTest_H  
  18. #define QueueTest_H  
  19. #include "Queue.h"  
  20.  
  21. void QueueTest_int()  
  22. {  
  23.  cout << endl << "整型队列测试" << endl;  
  24.  cout << endl << "构造一个空队列" << endl;  
  25.  Queue<int> a;  
  26.  cout << "将1~20入队,然后再出队" << endl;  
  27.  for (int i = 1; i <= 20; i++) a.EnQueue(i);  
  28.  while (!a.IsEmpty()) cout << a.DeQueue() << ' ';  
  29.  cout << endl;  
  30. }  
  31. #endif 

  没什么好说的,你可以清楚的看到,在单链表的基础上,栈和队列的实现是如此的简单。

  如读者希望继续阅读栈和队列的应用,请阅读拓展文章C++数据结构学习之栈的应用C++数据结构学习之队列的应用 。

【编辑推荐】

  1. 浅析C++栈使用方法
  2. 18.3.1 队列的概念
  3. 数据库使用C++数据结构
  4. 程序员必看 c++笔试题汇总
  5. c++编程常用工具
THE END