2017-06-18 94 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沒有意義,是內存泄漏的一個原因。