c++ - why after the first push head is still null? -


i trying create singly-linked list. after first push, head still null. why head not updated after first push?

using namespace std;  typedef struct node {     int data;        // store information     node *next;     // reference next node };  void push(node*,int); void print(node*);  int main() {     node* head = null;  //empty linked list     push(head, 2);     if (head == null) {         cout << "vrvrvr";     }     push(head, 3);     push(head, 5);     push(head, 2);     //print(head);     getchar();     return 0; }  void push(node* x, int y){     node *temp = new node();     if (x == null) { // check linked list empty         temp->next = x;         temp->data = y;         x = temp;      }     else {         node *temp1 = new node();         temp1 = x;         while (temp1->next != null) { // go last node             temp1 = temp1->next;         }         temp1->next = temp;         temp->data = y;         temp->next = null;         delete temp1; // 'temp' node last node     } }  void print(node* x){     node *temp1 = new node();     temp1 = x;     while (temp1->next != null) {         cout << temp1->data << endl;         temp1 = temp1->next;     } } 

the main problem push changes made x in function local function. not change value of head in main.

you can fix changing argument type node*&.

void push(node*& x, int y) {    ... } 

the other problems see in block:

else {     node *temp1 = new node();     temp1 = x;     // problem 1:     // after this, memory returned previous line lost.     // memory leak.      while (temp1->next != null) { // go last node         temp1 = temp1->next;     }     temp1->next = temp;     temp->data = y;     temp->next = null;     delete temp1; // 'temp' node last node     // problem 2:     // deleting node linked list.     // linked list has dangling pointer. } 

you can correct problems using:

    node *temp1 = x;     while (temp1->next != null) { // go last node         temp1 = temp1->next;     }     temp1->next = temp;     temp->data = y;     temp->next = null; } 

suggested improvements

  1. remove typedef definition of node. dangling typedef in posted code. also, can use node without typedef in c++.

    struct node {    int data;    node *next; }; 
  2. add constructor node.

    struct node {    node(int d) : data(d), next(nullptr) {}    int data;    node *next; }; 

    that simplify code in push.

    void push(node*& x, int y){    node *temp = new node(y);     if (x == null) { // check linked list empty       x = temp;    }    else {       node *temp1 = x;       while (temp1->next != null) { // go last node          temp1 = temp1->next;       }       temp1->next = temp;    } } 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -