Miket25
Miket25

Reputation: 1903

Trouble appending node to linked-list c++

I'm still new to C++. I'm having trouble with my append( ) function. 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.

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

Driver

#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.

Upvotes: 0

Views: 503

Answers (2)

Beta
Beta

Reputation: 99094

As I said above, append doesn't do well if tmp is null. 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;
}

Upvotes: 2

guozhu cheng
guozhu cheng

Reputation: 151

in the Driver:

node* empty_list = NULL;

but in append(), you use tmp->next which is "empty_list->next", this will cause segment fault

Upvotes: 0

Related Questions