作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
大家好 :) 所有这些都是新手所以如果我做错了什么请原谅。我目前正在做一项作业,我已经在这部分停留了很长一段时间。我想要做的是在线性链表的插入函数(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/
我是一名优秀的程序员,十分优秀!