棧&隊列&棧幀&遞歸

   *棧的定義——Stack

棧是隻允許在末端進行插入和刪除的線性表,棧具有後進先出的特徵(LIFO,Last In First Out).

     

   *棧的應用

棧很大意義上模擬了壓棧,實現了遞歸轉非遞歸。還有算術表達式求值,波蘭表達式(後綴表達式),迷宮問題等。

   *隊列的定義

隊列值允許在表的隊尾進行插入,在表對頭進行刪除。隊列具有先進先出的特性(FIFO,First In First Out).

    

 

1、優先級隊列的定義

每次從隊列中取出的都是最高優先級的數據,這種隊列就是優先級隊列。

——後續使用Heap實現

2、隊列的應用

(1)生產者消費者模型,如網絡數據buffer

(2)任務隊列

(3)圖的廣度優先遍歷

*一般函數的調用棧幀

*遞歸函數調用棧幀

*函數棧幀調用&數據結構棧幀--棧實現將遞歸程序轉換爲非遞歸程序

#include<iostream>
#include<stack>
using namespace std;
template<class T>
struct Node
{
public:
 Node(const T& x)
  :_data(x)
  ,_next(0)
 {}
 T _data;//數據
 Node* _next;//指向下個節點的指針
};
template<class T>
class SList
{
public:
 SList()
  :_head(0)
  ,_tail(0)
 {}
public:
 void PushBack(const T& x)
 {
  if(!_head)//鏈表爲空
  {
   _head=new Node<T> (x);
   _tail=_head;
  }
  else
  {
   _tail->_next=new Node<T> (x);
   _tail=_tail->_next;
  }
 }
 Node<T>* GetHead()
 {
  return _head;
 }
private:
 Node<T>* _head;
 Node<T>* _tail;
};
//逆序打印單鏈表遞歸實現
template<class T>
void PrintTailToHead_R(Node<T>* head)
{
 if(head)
 {
  PrintTailToHead_R(head->_next);
  cout<<head->_data<<" ";
 }
}
//逆序打印單鏈表非遞歸實現
template<class T>
void PrintTailToHead(Node<T>* head)
{
 stack<Node<T>*> s;
 while(head)
 {
  s.push(head);
  head=head->_next;
 }
 while(!s.empty())
 {
  cout<<s.top()->_data<<" ";
  s.pop();
 }
}
void Test()
{
 SList<int> s1;
 s1.PushBack(1);
 s1.PushBack(2);
 s1.PushBack(3);
 s1.PushBack(4);
 s1.PushBack(5);
 
 PrintTailToHead_R(s1.GetHead());
 cout<<endl;
 
 PrintTailToHead(s1.GetHead());
 cout<<endl;
}
int main()
{
 Test();
 return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章