PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

[FIXED] when I execute linked list using class it shows an extra zero

 August 17, 2022     c++, class, execution, linked-list, output     No comments   

Issue

#include<bits/stdc++.h>
#include<vector>
using namespace std;
class Node {
    public :
    int data;
    Node *next;

    Node()
    {
        data = 0;
        next = NULL;
    }
    Node (int a)
    {   data = a;
        next = NULL;
    }
};
void push(Node **head_ref , int n)
{  
    Node *new_node = new Node();
    new_node -> data = n;
    new_node -> next = *head_ref;
    *head_ref = new_node;}

void display(Node *head_ref)
{ while(head_ref != NULL)
    {
        cout << head_ref -> data << " ";
        head_ref = head_ref-> next;
    }
}
int main()
{   Node *head = new Node();
    push (&head  ,1 );
    push(&head ,0 );
    push(&head , 1);
    display(head);
    return(9);}

This when executed returns 1 0 1 0 as output , First i thought it is because of constructors but later I came to know that it is not something causing the problem.


Solution

Node *head = new Node();

Creates the extra node. Instead use

Node *head = nullptr;

or, if using an older compiler,

Node *head = NULL;

to point head at a safe location until legitimate nodes are added.



Answered By - user4581301
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing