2017-06-18 95 views
-1

我做了一个只有插入节点功能和打印功能的链接列表,但它不起作用。C++链接列表简单程序崩溃

#ifndef LIST_H_ 
#define LIST_H_ 
#include <iostream> 
using namespace std; 

struct Node{ 
    int data; 
    Node* next; 
}; 

class List{ 

private: 
    Node* head; 

public: 
    List(){ 
     head = NULL; 
    } 

    void insertEnd(int d){ 
     Node* newNode = new Node; 
     newNode->next = NULL; 
     newNode->data = d; 

     if (head == NULL){ 
      head = newNode; 
      return; 
     } 

     Node* cu = head; 

     while (cu != NULL) 
      cu = cu->next; 
     cu->next = newNode; 
    } 

    void printList(){ 
     Node* temp = new Node; 
     temp = head; 
     while (temp != NULL){ 
      cout << temp->data << ", "; 
      temp = temp->next; 
     } 
    } 

}; 

而我的主要功能:

#include <iostream> 
#include "List.h" 
using namespace std; 

int main(){ 

List list1; 

list1.insertEnd(1); 
list1.insertEnd(2); 
list1.insertEnd(3); 

//list1.printList(); 

return 0; 

}

该程序作品,如果我只插入一个节点,但如果我做任何事情它崩溃并没有给我任何错误迹象或任何事情。

我检查过几个网站,如果我的指针正在做正确的事情,我认为他们是,但是这里出了什么问题......?

编辑:固定的问题...在while循环应该是

while (cu->next != NULL) 
+0

它肯定会给你一个错误。如果你通过'bat'运行这个,在末尾添加一个'pause',这样你就可以读取错误。例如,'Node * cu = new Node',例如' – Carcigenicate

+1

'。 cu = head;' - 认为这存在意义? – RbMm

+0

insertEnd,printList() - 完全错误。 'Node * temp = new Node; temp = head;'这是C++? – RbMm

回答

1
void insertEnd(int d){ 
     Node* newNode = new Node; 
     newNode->next = NULL; 
     newNode->data = d; 

     if (head == NULL){ 
      head = newNode; 
      return; 
     } 

     Node* cu = head; 

     while (cu->next != NULL) 
      cu = cu->next; 
     cu->next = newNode; 
} 

更改为cu->next,此功能就可以了。你有一些相对简单的问题。首先,您试图制作头部副本以迭代您的列表。不是将它分配给虚拟指针,而是分配新内存,将新内存分配给虚拟指针,然后将头指针分配给该虚拟指针。这会造成内存泄漏,因为如果您忘记了内存,您将永远无法删除该内存。我改变了这一点:

Node* cu = new Node; 
cu = head 

这样:

Node* cu = head; 

其次,你分割的故障出现时,你是否立方米是不是在你的while循环空。您在循环中将cu设置为cu-> next,然后检查cu是否为空。如果cu为null,则将cu->分配给新节点。你的空指针没有引用任何内存,所以试图引用它的成员给你一个段错误。您想要访问链接列表中最后一个可能的有效指针。为此,请检查cu-> next是否为空。我改变了这一点:

while (cu != NULL) 
      cu = cu->next; 

这样:

while (cu->next != NULL) 
      cu = cu->next; 
1

while循环是不正确。从cu

while (cu->next != NULL) 
+1

谢谢你......愚蠢的错误 – Panthy

2

功能insertEnd是错误的。

这个循环

while (cu != NULL) 
     cu = cu->next; 

指针cv后等于NULL。因此,以下声明

cu->next = newNode; 

导致未定义的行为。

追加到列表中的一个节点的最简单方法如下

void insertEnd(int d) 
{ 
    Node **last = &head; 

    while (*last != nullptr) last = &(*last)->next; 

    *last = new Node { d, nullptr }; 
} 

的函数只有三行。:)

考虑到这种说法

Node* temp = new Node; 

在功能printList没有意义,是内存泄漏的一个原因。