[英]Trouble appending node to linked-list c++
I'm still new to C++. 我还是C ++的新手。 I'm having trouble with my append( ) function.
我的append()函数遇到问题。 I'm not allowed to change the parameters for this assignment.
我不允许更改此作业的参数。 I think the problem is I'm misinterpreting the argument being past.
我认为问题在于我误解了过去的论点。 I believe it's the address of the head node pointer?
我相信这是头节点指针的地址吗? But, when I compile and run the driver, I get a segmentation error.
但是,当我编译并运行驱动程序时,出现了分段错误。
#include <iostream>
struct node {
int data;
node* next;
};
node* init_node(int data);
std::string report(node* head);
void append_data(node** head, int data);
void append(node** head, node* new_node);
#include "linkList.h"
using namespace std;
node* init_node(int data) {
node* newNode = new node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
string report(node* root) {
string nodeData;
if(root->next != NULL){
nodeData = to_string(root->data)+" ";
while (root->next != NULL) {
nodeData = nodeData+(to_string(root->data)+" ");
root = root->next;
}
return nodeData;
}else{
return "";
}
}
void append_data(node** head, int data) {
node* newNode = init_node(data);
append(head, newNode);
}
//function causing problem
void append(node** head, node* new_node) {
node* tmp = *head;
while (tmp->next != NULL) {
tmp = newHead->next;
}
tmp->next = new_node;
}
#include "linkList.h"
#inlcude "linkList.cpp"
int main(){
cout << "Testing Linked List" << endl;
node* empty_list = NULL;
cout << "Empty List Contents: " << report(empty_list) << endl;
append_data(&empty_list, 16); //causing error here
cout << "Empty List Contents after appending 16: ";
}
I apologize if there are syntax errors. 如果出现语法错误,我深表歉意。 I tried to copy and paste what was only necessary since there is more this.
我尝试复制并粘贴仅需要的内容,因为还有更多内容。
As I said above, append
doesn't do well if tmp
is null. 正如我上面所说,如果
tmp
为null,则append
效果不佳。 When you are appending a new node to a list, appending to an empty list is a special case: 将新节点追加到列表时,在特殊情况下追加到空列表:
void append(node** head, node* new_node){
node* tmp = *head;
if(tmp==NULL) {
*head = new_node;
return;
}
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new_node;
}
in the Driver: 在驱动程序中:
node* empty_list = NULL;
but in append(), you use tmp->next which
is " empty_list->next
", this will cause segment fault 但是在append()中,您使用
tmp->next which
即“ empty_list->next
”,这将导致段错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.