c++ - Why head value not "NULL"? -


trying work out linked list problems. stuck basic mistake head value not "null" in createlinklist(). trick missing here . here code.

#include <iostream> using namespace std;  void createlinklist(struct node**); void showlist(); void insertnode();  struct node{     int data;     struct node * next; };  int main() {     struct node* head = null;     createlinklist(&head);     cout<<"inside main function \t"<<head<<endl;     return 0; } void createlinklist(struct node **head){     int data;     struct node * new_node;      cout<<"creating link list ..."<<endl;     cout<< "enter data inserted"<<endl;     cin >> data;     cout<<"inside createlinklist \t"<<head<<endl;     if (head == null){         new_node->data=data;         new_node->next=*head;         *head=new_node;         cout<<"element added @ head position"<<endl;     }     else{         cout<<"element added @ other positions"<<endl;     }  } 

output: enter image description here

cannot understand why head value different in main() , createlinklist().

your createlinklist method isn't taking head pointer, it's taking pointer-to-head pointer. should called phead:

void createlinklist(struct node **phead){ 

so head never null - should testing whether *head null.

but you've got way more problems that. you're not creating new node!

your code says (without debug lines):

struct node * new_node;    // <<< want new_node = new node;  if (head == null){         // <<< want *head here!     new_node->data=data;   // <<< variable uninitialised     new_node->next=*head;  // <<< know null - if said     *head=new_node; 

in short, need go drawing board.


Comments

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

laravel - Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id (View: F:\project\resources\views\admin\carousels\index.blade.php) -