gpt4 book ai didi

C++链表

转载 作者:行者123 更新时间:2023-11-30 01:00:55 26 4
gpt4 key购买 nike

我正在尝试使链表与此处的链表相似:

linked list in C

那就是在另一个结构中有“头”,我首先称它为“头”。但是我发现做那个改变。很难向 list_item 结构添加值。我已经尝试了一些东西,看看它是否有效。它编译,但是当我运行代码时它会崩溃。任何帮助在这里都会有所帮助。我知道崩溃的原因是我想将 new_node 指向 linked_list。

#include <iostream>

using namespace std;

struct list_item
{
int key;
int value;
list_item *next;
};

struct list
{
struct list_item *first;
};

int main()
{
list *head;
list *new_node;

head = NULL;
head->first = NULL;

for(int i = 0; i < 10; i++)
{
//allocate memory for new_node
new_node = (list*)malloc(sizeof(list));
new_node->first = (list_item*)malloc(sizeof(list_item));
//adding the values
new_node->first->key = i;
new_node->first->value = 10 + i;

//point new_node to first;
new_node->first->next = head->first;

//point first to new_node;
head->first = new_node->first;

}

//print
list *travel;
travel->first = head->first;

int i = 0;
while(travel != NULL)
{
cout << travel->first->value << endl;
travel->first = travel->first->next;
}

return 0;
}

最佳答案

您正在创建 10 个列表,我想您可以尝试这样做:

#include <iostream>

using namespace std;

struct list_item
{
int key;
int value;
list_item *next;
};

struct list
{
struct list_item *first;
};

int main()
{
//Just one head is needed, you can also create this
// on the stack just write:
//list head;
//head.first = NULL;
list *head = (list*)malloc(sizeof(list));
list_item *new_node = NULL;

head->first = NULL;

for(int i = 0; i < 10; i++)
{
//allocate memory for new_node
new_node = (list_item*)malloc(sizeof(list_item));
//adding the values
new_node->key = i;
new_node->value = 10 + i;

//if the list is empty, the element you are inserting
//doesn't have a next element

new_node->next = head->first;

//point first to new_node. This will result in a LIFO
//(Last in First out) behaviour. You can see that when you
//compile
head->first = new_node;

}

//print the list
list_item *travel;
travel = head->first;

while(travel != NULL)
{
cout << travel->value << endl;
travel = travel->next;
}

//here it doesn't matter, but in general you should also make
//sure to free the elements
return 0;
}

事情是这样的。一开始你只有一个头,没有元素。

head
|
|
V
NULL

然后添加第一个元素。确保“new_node->next==NULL”:

head
|
|
V
node: ------------------> NULL
key = 0
value = 10

然后您在前面添加另一个节点,但将您的第一个节点附加到它的下一个节点。您将指针从头部移动到新节点

head:
first
|
|
V
node: ---------> node: -------------> NULL
key: 1 key: 0
value: 11 value: 10

等等

由于您使用的是 C++,您可能会考虑使用“新建”和“删除”。只需更换

new_node = (list_item*)malloc(sizeof(list_item));

list *head = new list

关于C++链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1812706/

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