kuch ni smaj aaya . kya padaya h. lgta h hme bhi yaad krwa rhe h .kuch ni smaj aaya
Linked list insertiom
Hello @Priyanshu-Goel-1161416680732439,
There is no need to worry.
Pointers appear tough to understand in the beginning, but soon you’ll be able to catch things quickly.
Let’s understand this question with an example:
Suppose you have to create a linked list: A->B->C->D
where -> shows the link.
Linked lists are similar to arrays, structurally.
Each element(also known as node) in the linked list are present at distributed memory location unlike arrays.
In arrays elements are present at contiguous memory locations. Thus, they can easily be accessed by incrementing the index of array.
Now coming back to your question.
-
Define a class node(or you can give any other name):
class node{
char data;
node * next;
node(char d){ // this the constructor, which will be automatically evoked at the time of object declaration.
data=d;
next=NULL;
}
void insertAtHead(node *head, char d) //function to insert at head of link list
{
node *temp= new node(d); //make a new node and assign it with value dtemp->next=head; //*the node pointed by head earlier is now become the second node of the list, thus the next pointer of new node(which now the first node) will point to head(i.e the second node)
head = temp; //make new node as head.
}
};
…Here, data is a variable of type char to store value in the node.
…next is a pointer of type node(this means it will store the address of(or points to) the other objects of the class node)
…head is the a pointer of type node that points to the first element of the linked list.
- main of the program
int main(){
node n; //object of class node
node *head=NULL; // initially head will point to NULL(i.e. nothing)
n.insertAtHead(head,D);
n.insertAtHead(head,C);
n.insertAtHead(head,B);
n.insertAtHead(head,A);
return 0;
}
I have explained enough.
I would suggest you to dry run this program on paper to better understand the concept.
Hope, this would help.
Give a like, if you are satisfied.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
