麻烦将节点附加到链表c ++

时间:2015-05-18 04:06:46

标签: c++ linked-list

我还是C ++的新手。我的append()函数遇到了问题。我不允许更改此作业的参数。我认为问题是我误解了过去的论点。我相信它是头节点指针的地址?但是,当我编译并运行驱动程序时,我得到了分段错误。

linkList.h

#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);

linkList.cpp

#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: ";
}

如果有语法错误,我道歉。我试图复制并粘贴只有必要的东西,因为还有更多这个。

2 个答案:

答案 0 :(得分:2)

正如我上面所说,如果append为空,tmp并不好。当您将新节点附加到列表时,附加到列表是一种特殊情况:

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;
}

答案 1 :(得分:0)

在驱动程序中:

node* empty_list = NULL;

但在append()中,您使用tmp->next which是&#34; empty_list->next&#34;,这会导致段错误

相关问题