【发布时间】:2017-11-21 01:32:43
【问题描述】:
我创建了一个只有插入节点功能和打印功能的链接列表,但它不起作用。
#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; cu = head;- 认为这是存在意义吗? -
insertEnd, printList() - 完全错误。
Node* temp = new Node; temp = head;这是c++? -
如果您无法自己找出发生了什么,您可能需要使用调试器。仅供参考 cu->next = newNode 将始终崩溃,因为您的 while 循环没有检查正确的条件。它应该检查 while(cu->next != null)。您当前的实现在一定程度上确保您的指针在退出 while 循环之前是一个 nullptr...
-
cu->next = newNode;afterwhile (cu != NULL)- 所以 cu - 这里总是 0
标签: c++ linked-list append singly-linked-list