我做了一個只有插入節點功能和打印功能的鏈接列表,但它不起作用。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)
它肯定會給你一個錯誤。如果你通過'bat'運行這個,在末尾添加一個'pause',這樣你就可以讀取錯誤。例如,'Node * cu = new Node',例如' – Carcigenicate
'。 cu = head;' - 認爲這存在意義? – RbMm
insertEnd,printList() - 完全錯誤。 'Node * temp = new Node; temp = head;'這是C++? – RbMm