在链表末尾添加元素,在函数中指针值未被分配? (使用 code::blocks)
Adding element at end of a linked list, in function the pointer value not getting assigned? (using code::blocks)
我一直在尝试实现在链表末尾添加元素的功能,但它不起作用。
我尝试调试 code::blocks 中的代码,发现 "h->next = newNode;" 没有赋值。
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
};
void printlist(Node* h){
while(h->next!=nullptr){//or h!=0
cout<<h->data<<endl;
h = h->next;
}
}
void pushend(Node* h, int newData){
Node* newNode;
newNode = new Node;
newNode->data = newData;
newNode->next = nullptr;
while(h!=nullptr){
if(h->next == nullptr){
h->next = newNode;
break;
}
h = h->next;
}
}
int main(){
Node* head;
Node* second;
Node* third;
head = new Node;
second = new Node;
third = new Node;
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = nullptr;
int newData = 4;
pushend(head,newData);
printlist(head);
}
我不确定你所说的 h->next = newNode; is not assigning the value
是什么意思。
我可以看到您正在制作一个以 {1, 2, 3} 作为数据的列表,而不是在末尾添加 4 - 我还可以看到您的打印仅打印 1, 2, 3
。但这不是由 pushend
中的错误引起的。相反,这是因为你的 printlist
使用 while (h->next != nullptr)
循环,这意味着它永远不会打印你的最后一个元素(如果你在空列表上调用它它会崩溃(h = nullptr
)).
将您的 printlist
循环更改为 while (h != nullptr)
并且将打印所有四个元素。
我一直在尝试实现在链表末尾添加元素的功能,但它不起作用。
我尝试调试 code::blocks 中的代码,发现 "h->next = newNode;" 没有赋值。
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
};
void printlist(Node* h){
while(h->next!=nullptr){//or h!=0
cout<<h->data<<endl;
h = h->next;
}
}
void pushend(Node* h, int newData){
Node* newNode;
newNode = new Node;
newNode->data = newData;
newNode->next = nullptr;
while(h!=nullptr){
if(h->next == nullptr){
h->next = newNode;
break;
}
h = h->next;
}
}
int main(){
Node* head;
Node* second;
Node* third;
head = new Node;
second = new Node;
third = new Node;
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = nullptr;
int newData = 4;
pushend(head,newData);
printlist(head);
}
我不确定你所说的 h->next = newNode; is not assigning the value
是什么意思。
我可以看到您正在制作一个以 {1, 2, 3} 作为数据的列表,而不是在末尾添加 4 - 我还可以看到您的打印仅打印 1, 2, 3
。但这不是由 pushend
中的错误引起的。相反,这是因为你的 printlist
使用 while (h->next != nullptr)
循环,这意味着它永远不会打印你的最后一个元素(如果你在空列表上调用它它会崩溃(h = nullptr
)).
将您的 printlist
循环更改为 while (h != nullptr)
并且将打印所有四个元素。