我不知道为什么PrintList()不会终止。它是一个LinkedList,所以当我转到下一个时,它应该终止。 当我执行AddNode一次然后打印时,终止,当我执行addNode两次时,print不会终止。
我在构造函数中创建5个空白点的原因是因为我需要在程序启动时创建这5个空白点。
此外,如果我添加两次,如何指定指向第二个值的指针?
#pragma once
class LinkedList
{
private:
typedef struct node {
int data;
node* next;
}* nodePtr;
nodePtr n;
nodePtr head;
nodePtr curr;
nodePtr temp;
public:
LinkedList();
void AddNode(int addData);
void PrintList();
~LinkedList();
};
#include "LinkedList.h"
#include<cstdlib>
#include<iostream>
using namespace std;
LinkedList::LinkedList()
{
head = NULL;
curr = NULL;
temp = NULL;
n = new node;
for (int x = 1; x <= 5; x++) {
//cout << n<<endl;
n->next = n;
}
}
void LinkedList::AddNode(int addData) {
//nodePtr n = new node;
n->next = NULL;
n->data = addData;
cout << n <<endl;
if (head != NULL) {
curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
}
else {
head = n;
}
}
void LinkedList::PrintList() {
curr = head;
while (curr != NULL) {
cout << curr->data << endl;
curr = curr->next;
}
}
LinkedList::~LinkedList()
{
head = NULL;
curr = NULL;
temp = NULL;
delete n;
}
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "LinkedList.h"
using namespace std;
int main() {
LinkedList *l = new LinkedList();
l->AddNode(5);
l->AddNode(8);
l->PrintList();
system("pause");
return 0;
}
答案 0 :(得分:0)
由于您未将n设置为其他节点,因此节点n始终相同 因此,当您执行n-&gt; next和n-&gt;数据时,每次都会修改相同的节点
void LinkedList::AddNode(int addData) { //nodePtr n = new node; // you need to uncomment this n->next = NULL; n->data = addData; cout << n <<endl; if (head != NULL) { curr = head; while (curr->next != NULL) { curr = curr->next; } curr->next = n; } else { head = n; } } After your first addNode(5), lets examine the values. head = n head->data = 5 head->next = null After your second addNode(8) head = n head->data = 8 head->next = n // set by "curr->next = n" .
所以你这里有问题。当您尝试循环链接列表时,它将变为head-&gt; next-&gt; head-&gt; next-&gt; head-&gt; next-&gt; head-&gt; next .....导致无限环