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

#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->时,它应该向我显示选择项目的选项,但不会显示。在->此符号代码之后的其他代码位置也没有给我选择项目或下一个的可能性。请帮忙。

最佳答案

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;
};
  • int构造函数
  • 中删除了Queue类型的无名参数
  • 因为nodeNode而不是link,所以将Link重命名为Item,并且将Item重命名为item。只是为了使其变得标准化
  • tail的构造函数中初始化Queue
  • 在可能的情况下,使用初始化列表而不是代码。
  • 修复Queue::get(),如果队列为空,则将tail设置为零。
  • Queue::put()Queue::Node::Node()的参数列表中使用常量引用
  • NodeLinkheadtail从现在开始是私有(private)的。
  • Queue::empty()从现在开始返回bool而不是int
  • 09-10 04:38
    查看更多