[英]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無名參數 node
到Node
和link
到Link
,因為Item
是Item
,沒有item
。 只是為了使它有點標准化 Queue
的構造函數中初始化tail
。 Queue::get()
,如果隊列變空則將tail
設置為零。 Queue::put()
和Queue::Node::Node()
參數列表中使用常量引用 Node
, Link
, head
和tail
從現在開始是私有的。 Queue::empty()
從現在開始返回bool
而不是int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.