[英]C++ Linked List Not Preserving New Nodes
I'm trying to transition from an almost entirely Java background to getting comfortable with C++. 我正在尝试从几乎完全的Java背景过渡到对C ++的适应。 I'm practicing by trying to build a basic Linked List.
我正在尝试通过构建基本的链接列表进行练习。
#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;
}
}
};
The issue at hand is that once I add a new node using void addNode(string s)
, it does not appear when I attempt to print the list (starting from the head) with void printList()
. 当前的问题是,一旦我使用
void addNode(string s)
添加了新节点,当我尝试使用void printList()
从头开始打印列表时,它就不会出现。
For example: 例如:
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;
}
Using main() above, my results become: 使用上面的main(),我的结果变为:
This is your linked list: (string 1)
这是您的链接列表:(字符串1)
I'm pretty certain I'm using pointers improperly here but I don't see why. 我敢肯定,我在这里使用的指针不正确,但是我不明白为什么。 I've done as much digging as I can on my own for some clarification on how I could be doing this wrong but I'm coming up blank.
我已经尽我所能地进行了更多的挖掘工作,以弄清如何做错这个问题,但是我还是空白。
Thanks for any clarification you folks can provide. 感谢您提供的澄清。
The problem is here: 问题在这里:
node *temp = head->next;
while(temp != NULL)
temp = temp->next;
temp = newNode;
You're traversing the list, then setting temp
to the value of the newNode
. 您遍历该列表,然后将
temp
设置为newNode
的值。 When temp
goes out of scope, the value for newNode
isn't stored anyplace. 当
temp
超出范围时, newNode
的值不会存储在任何地方。
What you want to do is set the next
pointer of the last node
to the value of newNode
, ie 您要做的是将最后一个
node
的next
指针设置为newNode
的值,即
node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
The code above traverses the list until it finds a node
that doesn't have a next
node, and sets its next
node to the newNode
, thus adding it to the list. 上面的代码遍历该列表,直到找到一个
node
不具有next
节点,并设置其next
节点到newNode
,从而将其添加到列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.