Insertion of Linkedlist (all cases) 🫨🎊👍👍

  By : Himanshu Tiwari


#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};
void printLinkedlist(struct node *p) {
  while (p != NULL) {
    printf("%d ", p->data);
    p = p->next;
  }
}
struct node *insertatfirst(struct node *head,int data){
    struct node *ptr=(struct node *)malloc(sizeof(struct node));
    ptr->next=head;
    ptr->data=data;
    return ptr;

}
struct node *insertatindex(struct node *head,int data,int index){
    struct node *ptr=(struct node *)malloc(sizeof(struct node));
    struct node*p=head;
    int i=0;
    while (i!=index-1){
        p=p->next;
        i++;
    }
    ptr->data=data;
    ptr->next=p->next;
    p->next=ptr;
    return head;
}
struct node *insertatend(struct node *head,int data){
    struct node *ptr=(struct node *)malloc(sizeof(struct node));
    ptr->data=data;
    struct node*p=head;
    while (p->next!=NULL)
    {
        p=p->next;
    }
    p->next=ptr;
    ptr->next=NULL;
    return head;
}
struct node *insertafternode(struct node *head,struct node *prevnode,int data){
    struct node *ptr=(struct node *)malloc(sizeof(struct node));
    ptr->data=data;
    ptr->next=prevnode->next;
    prevnode->next=ptr;
    return head;
}
int main(){
    struct node *head;
    struct node *two;
    struct node *three;


    //memory allocation
    head=malloc(sizeof(struct node));
    two=malloc(sizeof(struct node));
    three=malloc(sizeof(struct node));

    head->data=10;
    head->next=two;

    two->data=20;
    two->next=three;

    three->data=30;
    three->next=NULL;

    printLinkedlist(head);
    printf("\n");
    // head=insertatindex(head,50,2);
    // head=insertatend(head,100);
    head=insertafternode(head,head,44);
    printLinkedlist(head);


    return 0;
}

Comments

Popular Posts