What is singly link list?
Singly link list is defined as:
singly link list is the type link list of data structure which move in forward direction because it does not move in backward direction. Singly link list is consists of no. of nodes, and each node having two parts which are given below:
1: Information part
2: Address part
Singly link list is whole packet which contains nodes and all data move only in forward direction.
Parts of singly Link List:
Singly link list consist of 3 parts:
1: Head part
2: Node
3: Tail part
Head part is also node but it is initial part for starting the every link list. It contain the address of first node and so no . when we have no node in our link list or no data in link list then head part is equal to NULL otherwise it contain the address of first node.
Tail is last part of link list which is equal to NULL.
Structure of Singly link list:
struct node
{
int data;
node*link;
};
Initialization of head pointer:
node*head=Null;
Logical Question: Why we take head pointer with node name?
Reason: because we take name of structure is node. An node is variable which contain different data types. so Head is data type which called node.
And first Head pointer is equal to NULL when no node is define.
int insert_node (int value)
{
node*ptr=new node;
ptr->data=value;
ptr->link=NULL;
head=ptr;
}
Explanation of this code:
if(head==NULL)
{
head=ptr;
}
else
{
node*temp=head;
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=ptr;
}
First we check is HEAD is equal to NULL then equalize the head to ptr. if not then first we make a temporary pointer which helps to insert node and firstly we equal the temp ptr to head and then start a while condition for checking NULL condition. whenever temporary pointer is not equal to NULL then we pass address of every node to temporary pointer in while condition. if temporary pointer is equal to NULL then while condition stop and equal the pointer ptr to link part of temporary pointer because new node address is pass to ptr pointer so that's why we equalize the temporary pointer to ptr for connecting new node through address.#include <iostream>
using namespace std;
struct node
{
int data;
node*link;
};
node*head=NULL;
int insert(int value)
{
node*ptr=new node;
ptr->data=value;
ptr->link=NULL;
if(head==NULL)
{
head=ptr;
}
else
{
node*temp=head;
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=ptr;
}
}
int main()
{
int a,value;
loop: cout<<endl<<"1:insert node"<<endl<<"enter choice : ";
cin>>a;
system("cls");
switch(a)
{
case 1:
cout<<"enter value of node : ";
cin>>value;
insert(value);
break;
default:
cout<<"Invalid Choice..!" ;
}
goto loop;
}
0 Comments