1.Simple linkedlist program to add a node at the front using c++ class.
//this is just a basic program to understand how a node is added into a linkedlist.
#include<iostream.h>
#include<conio.h>
class node
{
public:
int data;
node *next;
node()
{
data=0;
next=NULL;
}
node(int x)
{
data=x;
next=NULL;
}
};
class linked_list
{
node *head;
public:
int addNodeAtFront(node &n);
void display();
linked_list()
{
head=NULL;
}
};
int linked_list::addNodeAtFront(node &n) /*method declaraction*/
{
int i=0;
n.next=head; /*here adress inside the head is now given to next
head=&n; pointer of node class*/
i=1;
return i;
}
void linked_list::display()
{
node *ptr=head;
while(ptr!=NULL)
{
cout<<"\t"<<ptr->data;
ptr=ptr->next;
}
}
void main()
{
int x,q;
linked_list l;
clrscr();
cout<<"Enter a value:\t";
cin>>x;
node n(x);
q=l.addNodeAtFront(n); /*call to addNodeAtFront method of class Linked_list*/
if(q==1)
{
cout<<"Inserted";
l.display();
}
getch();
}
No comments:
Post a Comment