Answer to Question #234242 in C for SOM

Question #234242

Write the code to delete all the nodes in a doubly linked list, where the data element

of the node is greater than data element of all its previous nodes and is less than data

element of all the next nodes.




1
Expert's answer
2021-09-08T16:08:21-0400
#include <stdio.h>
#include <stdlib.h>
struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};
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->prev = NULL;
    new_node->next = (*head_ref);
    if ((*head_ref) != NULL)
        (*head_ref)->prev = new_node;
    (*head_ref) = new_node;
}
void deleteNode(struct Node** head_ref, struct Node* del)
{
    if (*head_ref == NULL || del == NULL)
        return;
    if (*head_ref == del)
        *head_ref = del->next;
    if (del->next != NULL)
        del->next->prev = del->prev;
    if (del->prev != NULL)
        del->prev->next = del->next;
    free(del);
    return;
}
void deleteGreaterNodes(struct Node** head_ref, int m)
{
    struct Node* ptr = *head_ref;
    struct Node* next;
 
    while (ptr != NULL) {
        next = ptr->next;
        if (ptr->data > m)
            deleteNode(head_ref, ptr);
        ptr = next;
    }
}
void printList(struct Node* head)
{
    while (head != NULL) {
        printf("%d", head->data);
        printf(" ");
        head = head->next;
    }
}
int main()
{
    struct Node* head = NULL;
    // 20<->18<->14<->21<->19
    push(&head, 19);
    push(&head, 21);
    push(&head, 14);
    push(&head, 18);
    push(&head, 20);
 
    int m = 19;
 
    printf("Original List: ");
    printList(head);
 
    deleteGreaterNodes(&head, m);
 
    printf("\nNew modified List: ");
    printList(head);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS