gpt4 book ai didi

C++ 链表不保留新节点

转载 作者:行者123 更新时间:2023-11-30 03:16:18 25 4
gpt4 key购买 nike

我正在尝试从几乎完全使用 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 的值不会存储在任何地方。

你要做的是将最后一个节点next指针设置为newNode的值,即

        node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;

上面的代码遍历列表,直到找到一个没有next节点的node,然后将它的next节点设置为newNode,从而将其添加到列表中。

关于C++ 链表不保留新节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com