我一直在学习链表。我正在编写以下代码以打印链接列表。但是它只是不会打印列表。有人可以帮我解决问题吗?
#include<iostream>
#include "getline.h"
using namespace std;
struct Node
{
string name, dream;
Node *randomptr;
};
Node *Populating(){
cout << "Enter name(press enter to exit): ";
string name = GetLine();
if(name == "") return NULL;
Node *newOne = new Node;
cout << "enter dream: ";
string dream = GetLine();
newOne->randomptr = NULL;
return newOne;
}
void PrintNode(Node *eachnode)
{
cout << eachnode-> name<<endl;
cout << eachnode-> dream << endl;
}
Node* BuilingLinkedList(){
Node *listHead = NULL;
while(true)
{
Node *newOne = Populating();
if(newOne == NULL) break;
newOne->randomptr=listHead;
listHead = newOne;
}
return listHead;
}
void PrintList(Node *list)
{
for(Node *cur = list; cur!= NULL; cur = cur->randomptr)
PrintNode(cur);
}
int main()
{
Node *list = BuilingLinkedList();
PrintList(list);
}
答案 0 :(得分:2)
Node *Populating(){
cout << "Enter name(press enter to exit): ";
string name = GetLine();
if(name == "") return NULL;
Node *newOne = new Node;
cout << "enter dream: ";
string dream = GetLine();
newOne->randomptr = NULL;
return newOne;
}
您没有对name
或dream
做任何事情。它们被读入局部变量,但从未分配给新节点。