无法将项目插入链接列表中
void LinkedList::insert(int num, int pos) {
Node *newNode = new Node;
newNode->data = num;
newNode->next = NULL;
if(pos == 0) {
newNode->next = head;
head = newNode;
}
else {
Node *temp = head;
for (int i = 1; i < pos-1; ++i) {
if (temp != NULL) {
temp = temp->next;
}
}
if (temp != NULL) {
newNode->next = temp->next;
temp->next = newNode;
}
else {
cout << " The previous node is full.";
}
}
}
这是我的插入功能。 在main.cpp中运行的代码是:
// adding through insert
nums.insert(1, 0);
nums.insert(5, 4);
nums.insert(3, 7);
输出是:
List after append:
8 6 7 8 0 9
List after inserting:
1 8 6 5 7 8
如您所见,某些东西被覆盖了,或者列表的结尾被切断了。我已经搜索了互联网几个小时,无济于事。输出需要增加列表的长度而不是覆盖任何内容。任何帮助将不胜感激。
void LinkedList::insert(int num, int pos) {
Node *newNode = new Node;
newNode->data = num;
newNode->next = NULL;
if(pos == 0) {
newNode->next = head;
head = newNode;
}
else {
Node *temp = head;
for (int i = 1; i < pos-1; ++i) {
if (temp != NULL) {
temp = temp->next;
}
}
if (temp != NULL) {
newNode->next = temp->next;
temp->next = newNode;
}
else {
cout << " The previous node is full.";
}
}
}
This is my insert function.
The code that runs in main.cpp is:
// adding through insert
nums.insert(1, 0);
nums.insert(5, 4);
nums.insert(3, 7);
And the output is:
List after append:
8 6 7 8 0 9
List after inserting:
1 8 6 5 7 8
As you can see, something is getting overwritten, or the end of the list just gets cut off. I have searched the internet for hours to no avail. The output needs to increase the length of the list and not overwrite anything. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,对于循环,
让我们假设
pos
等于2
。在这种情况下,循环不会迭代,temp
等于head
。因此,将在第二个模式之前插入新节点,而在第三个节点之前插入。您还需要编写
而不是编写此消息
(该函数的呼叫者应该决定是否输出消息),我将声明函数喜欢
并返回对是否插入节点的依赖。
The problem is this for loop
Let's assume that
pos
is equal to2
. In this case the loop will not iterate andtemp
will be equal tohead
. So the new node will be inserted before the second mode instead to be inserted before the third node.You need to write
Also instead of writing this message
(it is the caller of the function should decide whether to output a message) I would declare the function like
and return either true or false dependent on whether a node was inserted.