Linked List

Hi! everyone ,
I have created a little code to implement the linked list ,everything works fine but it is creating one exta node everytime a run this program ,so I'am attaching the code below ,help for fixing this bug . Thanks in advance .

Code :


#include<iostream>
#include<stdio.h>
using namespace std;

struct node{ //defining ADT
int data;
node* link;
};

typedef node* nodeptr; //giving name to node

nodeptr head=new node; //creating the head pointer

bool insertatfront(int n,nodeptr &head) //function to inserting a element
{

//i think the bug exist in this function

nodeptr newnode=new node;

if(!newnode) return false;

newnode->data=n;

newnode->link=head;

head=newnode; //it updating the local copy of the head only

return true;
}

bool remove(int n,nodeptr &head)
{
nodeptr newnode=new node;

if(!newnode) return false;

newnode=head;

n=newnode->data;
head=newnode->link;

delete newnode;

return true;

}


void show(nodeptr &head)
{
nodeptr current=new node;

current=head;

while(current!=NULL)
{
cout<<current->data<<endl;
current=current->link;
}

}


int count_nodes(nodeptr &head)
{
int count=0;

nodeptr current=new node;

current=head;

while(current!=NULL)
{
count++;
current=current->link;
}


return count;

}


int main()
{

insertatfront(4,head);
insertatfront(7,head);

cout<<"No of nodes in a linked list : "<<count_nodes(head)<<endl;
show(head);

remove(7,head);

cout<<endl;

cout<<"List after deleting :"<<endl;
show(head);


return 0;

}


o/p :

No of nodes in a linked list : 3
7
4
0

list after deleting :
4
0



# this zero is creating everytime(extra node why ?)
The extra node you're seeing is the initial empty node you create when you initialise head. But head should initially be null, and insert should deal with an empty head.
Topic archived. No new replies allowed.