C++ 链表不保留新节点
C++ Linked List Not Preserving New Nodes
我正在尝试从几乎完全 Java 的背景过渡到熟悉 C++。我正在通过尝试构建一个基本的链表来练习。
#include <iostream>
#include <string>
using namespace std;
struct node
{
string data;
node *next = NULL;
};
class linkedlist
{
public:
node *head;
public:
linkedlist()
{
head = NULL;
}
void addNode(string s)
{
node *newNode = new node;
newNode->data = s;
if(head == NULL)
head = newNode;
else
{
node *temp = head->next;
while(temp != NULL)
temp = temp->next;
temp = newNode;
}
}
void printList()
{
node *temp = head;
while(temp != NULL)
{
cout << temp->data << '\n';
temp = temp->next;
}
}
};
手头的问题是,一旦我使用 void addNode(string s)
添加了一个新节点,当我尝试使用 void printList()
打印列表(从头开始)时它不会出现。
例如:
int main(int argc, const char * argv[])
{
int n;
string str;
linkedlist list;
cout << "Please enter the number of strings you'd like to enter:\n";
cin >> n;
for(int i = 0;i < n;i++)
{
string temp;
cout << "Enter string #" << i + 1 << '\n';
cin >> temp;
list.addNode(temp);
}
cout << "This is your linked list: ";
list.printList();
return 0;
}
使用上面的 main(),我的结果变成:
This is your linked list:
(string 1)
我很确定我在这里不正确地使用了指针,但我不明白为什么。我已经尽可能多地自己进行挖掘,以澄清我是如何做错的,但我一无所获。
感谢大家提供的任何说明。
问题出在这里:
node *temp = head->next;
while(temp != NULL)
temp = temp->next;
temp = newNode;
您正在遍历列表,然后将 temp
设置为 newNode
的值。当 temp
超出范围时,newNode
的值不会存储在任何地方。
你要做的是将最后一个node
的next
指针设置为newNode
的值,即
node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
上面的代码遍历列表,直到找到一个没有next
节点的node
,并将其next
节点设置为newNode
,从而将其添加到列表中。
我正在尝试从几乎完全 Java 的背景过渡到熟悉 C++。我正在通过尝试构建一个基本的链表来练习。
#include <iostream>
#include <string>
using namespace std;
struct node
{
string data;
node *next = NULL;
};
class linkedlist
{
public:
node *head;
public:
linkedlist()
{
head = NULL;
}
void addNode(string s)
{
node *newNode = new node;
newNode->data = s;
if(head == NULL)
head = newNode;
else
{
node *temp = head->next;
while(temp != NULL)
temp = temp->next;
temp = newNode;
}
}
void printList()
{
node *temp = head;
while(temp != NULL)
{
cout << temp->data << '\n';
temp = temp->next;
}
}
};
手头的问题是,一旦我使用 void addNode(string s)
添加了一个新节点,当我尝试使用 void printList()
打印列表(从头开始)时它不会出现。
例如:
int main(int argc, const char * argv[])
{
int n;
string str;
linkedlist list;
cout << "Please enter the number of strings you'd like to enter:\n";
cin >> n;
for(int i = 0;i < n;i++)
{
string temp;
cout << "Enter string #" << i + 1 << '\n';
cin >> temp;
list.addNode(temp);
}
cout << "This is your linked list: ";
list.printList();
return 0;
}
使用上面的 main(),我的结果变成:
This is your linked list: (string 1)
我很确定我在这里不正确地使用了指针,但我不明白为什么。我已经尽可能多地自己进行挖掘,以澄清我是如何做错的,但我一无所获。
感谢大家提供的任何说明。
问题出在这里:
node *temp = head->next;
while(temp != NULL)
temp = temp->next;
temp = newNode;
您正在遍历列表,然后将 temp
设置为 newNode
的值。当 temp
超出范围时,newNode
的值不会存储在任何地方。
你要做的是将最后一个node
的next
指针设置为newNode
的值,即
node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
上面的代码遍历列表,直到找到一个没有next
节点的node
,并将其next
节点设置为newNode
,从而将其添加到列表中。