【问题标题】:Queue using linked list in c++在 C++ 中使用链表进行队列
【发布时间】:2016-11-04 13:56:14
【问题描述】:

我在使用链表程序的队列中有一个小错误。

程序成功执行,但是当我按 1 进行插入时,“输入要插入的元素”语句重复并且不返回主菜单。这是代码:

#include <iostream>
#include<conio.h>
using namespace std;

template<class T>
class node
{
    public:
        node<T> *next;
        T data;

};
template<class T>
class queue
{
    private:
        node<T> *head,*tail;
    public:
        queue();
        void enqueue(T &x);
        void dequeue();
        void display();        
};
template<class T>
queue<T>::queue()
{
    head=tail=NULL;

}
template<class T>
void queue<T>::enqueue(T &x)
{

node<T> *n=new node<T>;
n->data=x;
n->next=NULL;

    if(tail==NULL)
    {
        head=tail=n;
        return;
    }
        tail->next=n;
        tail=n;


}
template<class T>
void queue<T>::dequeue()
{
    if(head==NULL)
    {
        cout<<"EMPTY";
    }
    if(head==tail)
    {
        head=tail=NULL;
    }

    head=head->next;

}
template<class T>
void queue<T>::display()
{
    if(head==NULL)
    {
        cout<<"Empty";
        return;
    }
    cout<<"Queue elements are";
node<T> *temp=head;
while(temp!=NULL)
{
    cout<<"  "<<temp->data;
    temp=temp->next;
}
}
main()
{
queue<int> q;
int choice,ele;
cout<<"Main Menu \n 1. Insert \n 2.Delete \n 3.Display \n 4.Exit \n Enter your choice \n";
cin>>choice;
do
{
    switch(choice)
    {
        case 1: 
        {
            cout<<"Enter Element to insert";
            cin>>ele;
            q.enqueue(ele);
            break;

        }
        case 2:
            {
                q.dequeue();
                break;

            }
        case 3:
            {
                q.display();
                break;
            }
            case 4: 
            {
                cout<<"End of program";
                break;
            }
    }

}while(choice!=4);


}

【问题讨论】:

    标签: list linked-list queue


    【解决方案1】:

    问题出在main方法中:

    ...
    //WAS HERE
    //cout<<"Main Menu \n 1. Insert \n 2.Delete \n 3.Display \n 4.Exit \n Enter your choice \n";
    //cin>>choice;
    do
    {
        //SHOULD BE THERE
        cout<<"Main Menu \n 1. Insert \n 2.Delete \n 3.Display \n 4.Exit \n Enter your choice \n";
        cin>>choice;
        switch(choice)
        {
            case 1:
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多