c++ - Singly linked list, why is the list empty (head == NULL)? -


i created 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 empty." << endl;     }     else{         int = 1;         while (current != null){             cout << << ". 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 compile it, output this:

list empty.

but don't know why. "head" gets address, "head" shouldn't null. apparently null. don't know how solve problem.

you have remember arguments functions default passed value, means arguments value copied , function works on copy , not original.

now take append function, when pass head argument pointer copied argument, , changes made head inside function made copy.

to make work need pass arguments change by reference, like

void append(node *&head, node *&last, int data) 

now head , last references original pointer variables, , changes variable made original variables.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -