Delete a Node from Linked List (Beginning, End, Specified Position & Key)

 

Delete a Node from Linked List (Beginning, End, Specified Position & Key)



#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 *deleteatfirst(struct Node *head)
{
    struct Node *ptr;
    ptr = (struct Node *)malloc(sizeof(struct Node *));
    ptr = head;

    head = head->next;
    free(ptr);
    return head;
}

struct Node *deleteatindex(struct Node *head, int index)
{
    struct Node *p = head;
    struct Node *q = head->next;

    for (int i = 0; i < index - 1; i++)
    {
        p = p->next;
        q = q->next;
    }

    p->next = q->next;
    free(q);
    return head;
}

struct Node *deleteatlast(struct Node *head)
{
    struct Node *p = head;
    struct Node *q = head->next;

    while (q->next != NULL)
    {
        p = p->next;
        q = q->next;
    }

    p->next = NULL;
    free(q);
    return head;
}

struct Node *deleteatkey(struct Node *head, int value)
{
    struct Node *p = head;
    struct Node *q = head->next;

    while (q->data != value && q->next != NULL)
    {
        p = p->next;
        q = q->next;
    }

    if (q->data == value)
    {
        p->next = q->next;
        free(q);
    }
    return head;
}

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

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

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

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

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

    four->data = 45;
    four->next = NULL;

    printf("list befour deleting\n");
    printlist(head);
    printf("\nlist after deleting\n");
    // head = deleteatfirst(head);
    // head = deleteatindex(head, 1);
    // head = deleteatlast(head);
    head = deleteatkey(head, 3);

    printlist(head);







}






Post a Comment

0 Comments