gpt4 book ai didi

c++ - 如何在第一次出现 x(线性链表)C++ 后添加新元素 y

转载 作者:行者123 更新时间:2023-11-28 05:13:57 26 4
gpt4 key购买 nike

大家好 :) 所有这些都是新手所以如果我做错了什么请原谅。我目前正在做一项作业,我已经在这部分停留了很长一段时间。我想要做的是在线性链表的插入函数(int x,int y)上第一次出现元素“x”之后添加一个新元素“y”,它为其节点使用动态内存分配。很乐意感谢任何建议。感谢您的宝贵时间:)

#include <iostream>
using namespace std;
struct node {
int value;
node* next;
};
node* list = NULL;
node* first_item = new node();
void print() {

node* iterator = list;
if (iterator == NULL) {
cout << "EMPTY" << endl;
}
while (iterator != NULL)
{
cout << iterator->value; // print node value
if (iterator->next != NULL) {
cout << " -> ";
}
iterator = iterator->next; // progress to next value
}

cout << endl;
}
void insert(int y) { // adds a new element y as the first element in the list

first_item->value = y;
list = first_item; // point list to first item

}
void insert(int x, int y) { // adds a new element y after the first occurrence of element x


first_item->value = x;
node* second_item = new node(); // a second item
second_item->value = y;
second_item->next = first_item->next;
list->next = second_item;

}

int main()
{
node* list = NULL;
print();
insert(0);
print();
insert(0, 1);

print();
insert(1, 3);
print();
insert(1, 2);
print();
return 0;
}

我得到的错误输出值:

    EMPTY

0
0 -> 1
1 -> 3 -> 1
1 -> 2 -> 3 -> 1

以及我需要的正确值:

    EMPTY
0
0 -> 1
0 -> 1 -> 3
0 -> 1 -> 2 -> 3

最佳答案

你有设计问题。

首先,删除全局变量:

#include <iostream>
using namespace std;
struct node {
int value;
node* next;
};
node* list = NULL; // This
node* first_item = new node(); // And this

每个函数都应该有一个参数:列表的第一个节点。就是这样。如果你需要列表的最后一个元素,你应该迭代到最后:

void print(node* list) { 

node* iterator = list;
if (iterator == NULL) {
cout << "EMPTY" << endl;
}
while (iterator != NULL)
{
cout << iterator->value; // print node value
if (iterator->next != NULL) {
cout << " -> ";
}
iterator = iterator->next; // progress to next value
}

cout << endl;
}
void insert(node* first_item,int y) { // adds a new element y as the first element in the list

//TODO Implement

}
void insert(int x, int y) { // adds a new element y after the first occurrence of element x

//TODO Implement
}

int main()
{
node* list = NULL;

print(list);
insert(list,0);
print(list);
insert(0, 1);

print(list);
insert(1, 3);
print(list);
insert(1, 2);
print(list);
return 0;
}

关于c++ - 如何在第一次出现 x(线性链表)C++ 后添加新元素 y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43028278/

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