簡體   English   中英

FIFO隊列鏈表實現

[英]FIFO Queue linked list implementation

這是我嘗試使用鏈表實現隊列的代碼:

#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->它應該顯示我選擇項目的選項,但它沒有顯示。 在其他代碼之后 - >這個符號代碼不允許我選擇項目或下一個。 請幫忙。

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

例如,STL顯式包含一個queue容器適配器(默認情況下基於deque ,這是最有效的選擇)。

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

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

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;
};
  • Queue構造函數中刪除了int typed無名參數
  • 更名nodeNodelinkLink ,因為ItemItem ,沒有item 只是為了使它有點標准化
  • Queue的構造函數中初始化tail
  • 盡可能使用初始化列表而不是代碼。
  • 修復Queue::get() ,如果隊列變空則將tail設置為零。
  • Queue::put()Queue::Node::Node()參數列表中使用常量引用
  • NodeLinkheadtail從現在開始是私有的。
  • Queue::empty()從現在開始返回bool而不是int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM