2013-03-26 55 views
0

我写的执行队列链表的代码,但我不能找出一些bug。当我第一次将一个项目推入队列时,它可以找到,但是当我尝试推入第二个项目时,它会给我带来运行时错误。你能帮我一下吗?非常感谢你! 以下是代码:执行队列链表

#include<iostream> 
using namespace std; 
template<typename T> 
struct Node{ 
    T data; 
    Node* next; 
    Node(T d, Node* n=NULL): data(d), next(n){} 
}; 


template<typename T> 
class myqueue{ 
    private: 
     Node<T> * first; 
     Node<T> * last; 
    public: 
     myqueue(){} 
     void push(T da){ 
      if(first==NULL) { 
       first=new Node<T>(da); 
       last=first; 
      } 
      else { 

       last->next=new Node<T>(da); 
       last=last->next; 

       } 
     } 
     void pop(){ 
      if(last!=NULL){ 
      Node<T> * temp=first; 
      first=first->next; 
      delete temp; 
      } 
     } 
     void front(){ 
      if(first!=NULL) cout<< first->data; 
     } 
     bool isempty(){ 
      return last==NULL; 
     } 
}; 

int main(){ 
    myqueue<int> q; 
    q.push(1); 
    q.push(2); 
    q.front(); 
    /* 
    q.push(3); 
    q.push(4); 
    q.push(5); 
    cout<<q.front(); 
    */ 

} 


compile error: runtime error  

回答

4

firstlast指针是未初始化的,所以你必须未定义的行为。有成员初始化列表初始化它们:

myqueue::myqueue() : first(NULL), last(NULL) {} 
+0

非常感谢您! – diane 2013-03-26 19:32:41

+0

难道我应该总是初始化一个指针吗? – diane 2013-03-26 19:33:19

+0

@dianedan你不应该使用未初始化变量的值。这是初始化成员指针的一种方法。或者,您可以在构造函数中为它们分配“NULL”('first = NULL; last = NULL;')。 – 2013-03-26 19:35:41