Linked List | (Inserting a node)

 Linked List |  (Inserting a node) 



#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node *next;
};

void printlist(struct Node *ptr)
{

    while (ptr != NULL)
    {
        printf("%d\n", ptr->data);
        ptr = ptr->next;
    }
}

struct Node *insertatfirst(struct Node *head, int data)
{
    struct Node *ptr;
    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;
    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 *));
    struct Node *ptr;
    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 *));
    struct Node *ptr;
    ptr = (struct Node *)malloc(sizeof(struct Node *));
    ptr->data = data;

    ptr->next = prevnode->next;
    prevnode->next = ptr;
    return head;
}

int main()
{
    struct Node *head = NULL;
    struct Node *second = NULL;
    struct Node *thrid = NULL;

    head = (struct Node *)malloc(sizeof(struct Node));
    second = (struct Node *)malloc(sizeof(struct Node));
    thrid = (struct Node *)malloc(sizeof(struct Node));

    head->data = 1;
    head->next = second;

    second->data = 2;
    second->next = thrid;

    thrid->data = 3;
    thrid->next = NULL;

    printf("list befour inserted\n");
    printlist(head);
    printf("\nlist after inserted\n");
    // head = insertatfirst(head, 15);
    // head = insertatindex(head, 115, 2);
    // head = insertatEnd(head, 222);
    head = insertafternode(head, second, 554);

    printlist(head);
    }





Post a Comment

0 Comments