FIFO队列链表实现

时间:2010-08-30 12:21:46

标签: c++

以下是我尝试使用链接列表实现队列的代码:

#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->时,它应该显示我选择项目的选项,但它没有显示。也在其他代码之后 - &gt;这个标志代码不允许我选择项目或下一个。请帮忙。

2 个答案:

答案 0 :(得分:3)

重新使用现有容器可能会更好。

STL明确包含一个queue容器适配器(默认情况下基于deque,这是最有效的选择)。

如果您不需要多态行为,那么std::queue<Item>就是您正在寻找的,它既非常高效(超过您的自定义列表队列),您将避免内存管理问题。

如果您需要多态行为,请使用std::queue< std::unique_ptr<Item> >

答案 1 :(得分:3)

ON: - &gt;运算符可以重载,因此开发环境无法确定如何处理它。如果您真的想要自动完成,可以执行以下操作(暂时或永久)。

// 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;
};
  • int构造函数
  • 中删除了Queue类型无名参数
  • node重命名为Node,将link重命名为Link,因为ItemItem,而非item。只是为了使它有点标准化
  • tail的构造函数中初始化Queue
  • 尽可能使用初始化列表而不是代码。
  • 修复Queue::get(),如果队列变空,则将tail设置为零。
  • Queue::put()Queue::Node::Node()
  • 的参数列表中使用常量引用
  • NodeLinkheadtail从现在开始是私有的。
  • Queue::empty()从现在起返回bool而不是int
相关问题