How to delete one specific node in linked list in C ThanksSo

How to delete one specific node in linked list in C?

Thanks

Solution

#include <stdio.h>

#include <stdlib.h>

struct node

{

    int data;

    struct node *next;

};

void deleteNode(struct node *head, struct node *n)

{

    if(head == n)

    {

        if(head->next == NULL)

        {

            printf(\"There is only one node. The list can\'t be made empty \");

            return;

        }

        head->data = head->next->data;

        n = head->next;

        head->next = head->next->next;

        free(n);

        return;

    }

    struct node *prev = head;

    while(prev->next != NULL && prev->next != n)

        prev = prev->next;

        if(prev->next == NULL)

    {

        printf(\"\ Given node is not present in Linked List\");

        return;

    }

        prev->next = prev->next->next;

    free(n);

    return;

}

void push(struct node **head_ref, int new_data)

{

    struct node *new_node =

        (struct node *)malloc(sizeof(struct node));

    new_node->data = new_data;

    new_node->next = *head_ref;

    *head_ref = new_node;

}

void printList(struct node *head)

{

    while(head!=NULL)

    {

        printf(\"%d \",head->data);

        head=head->next;

    }

    printf(\"\ \");

}

int main()

{

    struct node *head = NULL;

    push(&head,3);

    push(&head,2);

    push(&head,6);

    push(&head,5);

    push(&head,11);

    push(&head,10);

    push(&head,15);

    push(&head,12);

    printf(\"Given Linked List: \");

    printList(head);

    printf(\"\ Deleting node %d: \", head->next->next->data);

    deleteNode(head, head->next->next);

    printf(\"\ Modified Linked List: \");

    printList(head);

    printf(\"\ Deleting first node \");

    deleteNode(head, head);

    printf(\"\ Modified Linked List: \");

    printList(head);

    getchar();

    return 0;

}

How to delete one specific node in linked list in C? ThanksSolution#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next;
How to delete one specific node in linked list in C? ThanksSolution#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next;
How to delete one specific node in linked list in C? ThanksSolution#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next;

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site