2016-11-04 72 views
0

我在使用鏈表程序的隊列中有一個小錯誤。在C++中使用鏈表的隊列

程序執行成功,但是當我按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); 


} 

回答

0

的問題是主要方法:

... 
//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: 
...