gpt4 book ai didi

c++ - 如何打印一个简单的链表(C++)?

转载 作者:行者123 更新时间:2023-11-27 23:53:36 27 4
gpt4 key购买 nike

我做的代码是这样的:

struct node
{
int value;
node *prev;
node *next;
};

void play()
{
node *head = NULL, *temp = NULL, *run = NULL;

for (int x = 1; x > 10; x++)
{
temp = new node(); //Make a new node
temp -> value = x; //Assign value of new node
temp -> prev = NULL; //Previous node (node before current node)
temp -> next = NULL; //Next node (node after current node)
}
if (head == NULL)
{
head = temp; //Head -> Temp
}
else
{
run = head; //Run -> Head
while (run -> next != NULL)
{
run = run -> next; //Go from node to node
}
run -> next = temp; //If next node is null, next node makes a new temp
temp -> prev = run;
}
run = head; //Play from start again
while (run != NULL) //Printing
{
printf("%d\n", run -> value);
run = run -> next;
}
}


int main()
{
play();
system ("pause");
return 0;
}

但是,它不起作用。没有输出(完全空白)。我怎样才能让这个链接列表正确打印?我希望它输出:

1 2 3 4 5 6 7 8 9 10

我的其他选择是为打印创建另一个单独的函数或将整个函数移至 int main,但我已经尝试过了,但它仍然没有输出任何内容。

最佳答案

对于初学者来说,函数中第一个 for 循环的条件有一个拼写错误

for (int x = 1; x > 10; x++)
^^^^^^

必须有

for (int x = 1; x <= 10; x++)
^^^^^^

其次,尝试将新节点添加到列表的代码在 for 循环之外。因此只有最后分配的节点才会被添加到列表中。您必须将代码放在循环中。

此外,如果这是一个双链表,那么最好有一个尾节点,新节点将附加到该尾节点。

并且您应该在退出该函数之前释放所有分配的内存。

该函数在演示程序中显示如下所示。

#include <iostream>
#include <cstdlib>

struct node
{
int value;
node *prev;
node *next;
};

void play()
{
const int N = 10;
node *head = nullptr, *tail = nullptr;

for (int i = 0; i < N; i++)
{
node *temp = new node{ i + 1, tail, nullptr };

if (tail == nullptr)
{
head = tail = temp;
}
else
{
tail = tail->next = temp;
}
}

for (node *current = head; current != nullptr; current = current->next)
{
std::cout << current->value << ' ';
}
std::cout << std::endl;

while (head != nullptr)
{
node *temp = head;
head = head->next;
delete temp;
}
tail = head;
}

int main()
{
play();
// system("pause");

return 0;
}

程序输出为

1 2 3 4 5 6 7 8 9 10 

您可以通过添加一个指定所创建列表中的节点数的参数来使该函数更加灵活,而不是使用魔数(Magic Number) 10

例如

void play( int n )
{
node *head = nullptr, *tail = nullptr;

for (int i = 0; i < n; i++)
{
node *temp = new node{ i + 1, tail, nullptr };

if (tail == nullptr)
{
head = tail = temp;
}
else
{
tail = tail->next = temp;
}
}

for (node *current = head; current != nullptr; current = current->next)
{
std::cout << current->value << ' ';
}
std::cout << std::endl;

while (head != nullptr)
{
node *temp = head;
head = head->next;
delete temp;
}
tail = head;
}

在这种情况下,函数可以像这样调用

play( 10 );

play( 20 );

等等。

关于c++ - 如何打印一个简单的链表(C++)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44323306/

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