Related list: Difference between "node * head = new node" and "node * head"

I am creating a list of links of size n entered by the user. That's when I just initialize the header, the output is perfect, but when I declare it, the output also has two zeros.

For size = 5 If I write node * head = new node; the output is 432100, and if I write only node * the head output is 43210. Why is this?

/* I am creating a link list of size n entered by user
 * File:   main.cpp
 * Author: neha
 *
 * Created on February 2, 2014, 12:39 AM
 */

#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;

/*
 * 
 */
using namespace std;
struct node{
    int data;
    node* next;
};
node* head=new node; //<--------------here
void PushFront(int value) //Inserting nodes at front of link list
{
    node* newNode= new node;
    newNode->data=value;
    newNode->next=head;
    head=newNode;

}

void Print() //printing the inserted nodes
{
    node* temp= new node;
    temp=head;


    while(temp!=NULL)
    {
        cout<< temp->data;
        temp=temp->next;
    }
}

int main()
{
int size,i;
cout<<"Enter size of linked list"<<endl;//Asking user to enter the size of linklist
cin>>size;
for(i=0;i<size;i++)
{
PushFront(i);
}

Print();
return 0;
}
+4
source share
3 answers

If you simply declare node* head, then the value headis undefined ("garbage"), and you should refrain from using it.

Additional problem in your code:

node* temp= new node;
temp=head;

, , temp = something, temp = something else. , , . , "" .

+1

: undefined.

node* head=new node

head node, . head->next = <Garbage>.

       _________
      |DATA|NEXT|
head->|----|----|
      |Junk|Junk|      
      |____|____|

After 1st Insert

       _________    _________
      |DATA|NEXT|  |DATA|NEXT|
head->|----|----|  |----|----|
      |  0 |----|->|Junk|Junk|      
      |____|____|  |____|____|


After nth Insert

       _________      _________    _________
      |DATA|NEXT|    |DATA|NEXT|  |DATA|NEXT|
head->|----|----|    |----|----|  |----|----|
      |  n |----|...>| 0  |----|->|Junk|Junk|      
      |____|____|    |____|____|  |____|____|

node* head;

head undefined.

head->Junk

After nth Insert

       _________      _________   
      |DATA|NEXT|    |DATA|NEXT|  
head->|----|----|    |----|----|  
      |  n |----|...>| 0  |----|->Junk
      |____|____|    |____|____|  

, , node, undefined.

, , () node.

node* head=nullptr;

nullptr

head->nullptr

After nth Insert

       _________      _________   
      |DATA|NEXT|    |DATA|NEXT|  
head->|----|----|    |----|----|  
      |  n |----|...>| 0  |----|->nullptr
      |____|____|    |____|____|  
+1

, undefined , . undefined, , .

, undefined.

, . node* next;, undefined , .

- ,

node() : data(0), next(nullptr){}

node* temp= new node;
temp=head;

node , .

node* temp = head;
0
source

Source: https://habr.com/ru/post/1524912/


All Articles