2010-08-30 309 views
4

這是在我試圖用鏈表來實現隊列代碼:FIFO隊列鏈表實現

#include <iostream> 
#include <cstdlib> 
using namespace std; 
template <class Item> 
class Queue{ 

public: 
    struct node{ 
     Item item;node *next; 
     node (Item x){ 
     item=x; next=0; 
     } 
    }; 
    typedef node* link; 
    link head, tail; 

public: 
    Queue(int){ head=0;} 
    int empty() const { return head==0; } 
    void put(Item x){ 

     node* t=tail; 
     tail=new node(x); 
     if (head==0) head=tail; 
     else t->next=tail; 
    } 
    Item get(){ 

     Item v=head->item;link t=head->next; 
     delete head; head=tail return v; 
    } 

    }; 

int main(){ 
    return 0; 
} 

,但我有指針的問題。例如,當我寫Item v = head->它應該顯示我選擇項目的選項,但它不顯示。也在其他地方的代碼 - >這個標誌碼不給我選擇項目或下一個的可能性。請幫忙。

+1

您可以發佈具體的問題,包括適當的錯誤輸出,錯誤消息和所需的輸出。也請使用句子,你的問題很難閱讀。 – 2010-08-30 12:26:27

+0

考慮'它應該讓我選擇':你想讓你的IDE(你的編輯器)顯示一個'head's成員列表嗎?或者是其他東西? – phimuemue 2010-08-30 12:26:33

+0

是的成員,但它不顯示我 – 2010-08-30 12:36:21

回答

3

ON: - >操作符可能被重載,因此開發環境無法確定如何處理它。如果您確實想要自動完成,您可以執行以下操作(暫時或永久)。

// IMPORTANT. Make sure "head" is not null before you do it! 
Node &headNode(*head); // Create a reference 
headNode.next = tail; // Use TAB or CTRL+SPACE or whatever here after dot 

OFF:我檢查了您的代碼,並取得了一定的修正

template <class Item> 
class Queue { 
public: 
     Queue() 
     : head(0) 
     , tail(0) 
     { } 
     bool empty() const { return head==0; } 
     void put(const Item& x) 
     { 
       Node* t = tail; 
       tail = new Node(x); 
       if (head==0) 
         head = tail; 
       else 
         t->next = tail; 
     } 
     Item get() 
     { 
       Item v = head->item; 
       Link t = head->next; 
       delete head; 
       head = t; 
       if(head==0) 
         tail = 0; 
       return v; 
     } 
private: 
     struct Node { 
       Item item; 
       Node *next; 
       Node(const Item& x) 
       : item(x) 
       , next(0) 
       {} 
     }; 
     typedef Node* Link; 
     Link head,tail; 
}; 
  • 刪除intQueue構造
  • 更名nodeNodelinkLink因爲ItemItem類型的無名參數,而不是item。只是爲了使它有點標準化
  • 初始化tail構造函數Queue
  • 儘可能使用初始化程序列表而不是代碼。
  • 修復Queue::get(),如果隊列變空,則將tail設置爲零。
  • 使用的Queue::put()參數列表和恆定的參考Queue::Node::Node()
  • NodeLinkheadtail是私人從現在開始。
  • Queue::empty()從現在開始返回bool而不是int
3

重複使用現有容器可能會更好。

STL明確包含,例如,一個queue容器適配器(根據默認deque,這是最有效的選擇)。

如果您不需要多態行爲,那麼您正在尋找std::queue<Item>,它非常高效(不僅僅是基於自定義列表的隊列),而且您將避免內存管理問題。

如果您需要多態行爲,請使用std::queue< std::unique_ptr<Item> >

+1

「不要重新發明輪子,除非你打算更多地瞭解輪子。」 – Mizipzor 2010-08-30 12:39:47

+1

我認爲你過度設計答案。他在編輯的自動完成功能方面存在問題。 – celavek 2010-08-30 12:47:40

+1

@cevalek:我想也是這樣,但在評論之前並不清楚。有趣的是,我仍然爲此付出了努力,所以我想我不是唯一一個沒有接受真正問題的人。 – 2010-08-30 12:53:31