Reputation: 1497
I created a singly linked list:
#include <iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
bool isEmpty(Node *head){
if (head == NULL){
return true;
}
else{
return false;
}
}
void append(Node *head, Node *last, int data){
Node *newNode = new Node;
newNode->data = data;
newNode->next = NULL;
if (isEmpty(head)){
head = newNode;
last= newNode;
}
else{
last->next = newNode;
last= newNode;
}
}
void printList(Node *current){
if (isEmpty(current)){
cout << "List is empty." << endl;
}
else{
int i = 1;
while (current != NULL){
cout << i << ". Node: " << endl;
cout << current->data << endl;
current = current->next;
i++;
}
}
}
void main(){
Node *head = NULL;
Node *last = NULL;
append(head, last, 53);
append(head, last, 5512);
append(head, last, 13);
append(head, last, 522);
append(head, last, 55);
printList(head);
}
When I compile it, the output is this:
List is empty.
But I don't know why. "head" gets an address, so "head" shouldn't be NULL. But apparently it is NULL. I don't know how to solve this problem.
Upvotes: 0
Views: 3843
Reputation: 1122
Pass the address of the head and last variable and it sholud work.
append(&head, &last, 53);
and changes in the append function as below
void append(Node **head, Node **last, int data)
Upvotes: 0
Reputation: 409166
You have to remember that arguments to functions are by default passed by value, which means that the arguments value is copied and the function only works on the copy and not the original.
Now take the append
function, when you pass the head
argument the pointer is copied into the argument, and any changes made to head
inside the function is only made to that copy.
To make it work you need to pass the arguments you change by reference, like
void append(Node *&head, Node *&last, int data)
Now head
and last
are references to the original pointer variables, and changes to the variable are made to the original variables.
Upvotes: 4
Reputation: 1406
In the function : append(Node *head, Node *tail, int data)
you should pass head
and tail
by reference. In your approach when you are assigning head = newNode
then it is being assigned to a local copy of head
and not the head
that you passed.
Upvotes: 1
Reputation: 172924
The parameter head
and last
are passed by value, so the change of them inside the function append
has nothing to do with the outside variables, they are independent.
You need to pass it by reference or pointer of pointer, such as:
void append(Node *&head, Node *&last, int data) {
Upvotes: 1