我做了一个只有插入节点功能和打印功能的链接列表,但它不起作用。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