2012-05-18 48 views
0

我想做一个int值的链表。我添加3个int值列表,并打印它们,但我的问题打印3个值后,程序返回到打印功能打印第四个因为(tempNode!= NULL)给出true,但打印后应为NULL 3值,所以它给我在访问冲突读取错误在打印方法在cout << "index " << size-- << ", value: "<< tempNode->num << endl;访问冲突阅读位置:链接列表C++

它超出了我的列表节点,但我不知道哪里做错了。

请帮忙,2天试图弄清楚这一点。

以下代码。

IntList::IntList() 
{ 
    first = NULL; 
    last = NULL; 
    size = 0; 
} 


IntList::Node::Node(const int& info, Node* next = NULL) 
{ 
    num = info; 
    next = next; 
} 


IntList::~IntList() 
{ 
    Node* tempNode = first; 
    while (tempNode != NULL) 
    //for(int i = 0; i < size; i++) 
    { 
     Node* nextNode = tempNode->next; 
     delete tempNode; 
     tempNode = nextNode; 
    } 

    first = last = NULL; 
    size = 0; 
    } 


IntList::IntList(const IntList& wl) 
{ 
    cout << "here word list copy conts " << endl; 

    first = last = NULL; 
    size = wl.size; 
    if(wl.first != NULL){ 

     Node* tempNode = wl.first; 
     for(int i = 0; i < wl.size; i++) 
     { 
       addLast(tempNode->num); 
       tempNode = tempNode->next; 
     } 
    } 
} 


IntList& IntList::operator = (const IntList& wl) 
{ 
    cout << "here word list =" << endl; 
    if(this == &wl) 
     return *this; 

    Node* tempNode = first; 
    while (tempNode != NULL) 
    { 
     Node* nextNode = tempNode->next; 
     delete tempNode; 
     tempNode = nextNode; 
    } 

    first = NULL; 
    last = NULL; 

    if(wl.first != NULL) 
    { 
     for(int i = 0; i < wl.size; i++) 
     { 
      addLast(tempNode->num); 
      tempNode = tempNode->next; 
      size++; 
    } 
} 

return *this; 
} 

void IntList::addFirst(int& winfo) 
{ 
    Node* firstNode = new Node(winfo); 
    //Node firstNode(winfo); 
    if(first == NULL) 
    { 
     first = last = firstNode; 
    } 
    else 
    { 
     firstNode->next = first; 
     first = firstNode; 
    } 
    //increment list size 
    size++; 
} 

void IntList::print(ostream& out) 
{ 
    Node* tempNode = first; 
    while (tempNode != NULL) 
    { 
     out << "\t"; 
     cout << "index " << size-- << ", value: "<< tempNode->num << endl; 
     tempNode = tempNode->next; 
    } 
} 
+0

你可以减少这个*最小*但完整的例子,演示你遇到的问题?我们可以编译并运行,而无需修改它。 –

+0

“addLast”在哪里? – Joe

+0

我可以提供我的头文件,是吗? – newbieLinuxCpp

回答

2

构造Nodenext参数阴影其next构件,所以next = next被分配给参数。
重命名其中一个。

此外,在打印时不要修改size

+0

谢谢,它现在的作品没有错误消息 – newbieLinuxCpp