Eliminar todos los Nodes de la lista que sean mayores que x

Dada una lista enlazada, el problema es eliminar todos los Nodes de la lista que son mayores que el valor x especificado . Ejemplos:

Input : list: 7->3->4->8->5->1
        x = 6
Output : 3->4->5->1

Input : list: 1->8->7->3->7->10
        x = 7
Output : 1->7->3->7

Fuente: Experiencia de entrevista de Microsoft | Conjunto 169.

Enfoque: esta es principalmente una variación de la publicación que elimina la primera aparición de una clave determinada. Primero debemos verificar todas las ocurrencias en el Node principal que son mayores que ‘x’, eliminarlas y cambiar el Node principal de manera adecuada. Luego, debemos verificar todas las ocurrencias dentro de un ciclo y eliminarlas una por una. 

CPP

// C++ implementation to delete all the nodes from the list
// that are greater than the specified value x
#include <bits/stdc++.h>
   
using namespace std;
   
// structure of a node
struct Node {
    int data;
    Node* next;
};
   
// function to get a new node
Node* getNode(int data)
{
    Node* newNode = new Node;
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}
   
// function to delete all the nodes from the list
// that are greater than the specified value x
void deleteGreaterNodes(Node** head_ref, int x)
{
    Node *temp = *head_ref, *prev;
   
    // If head node itself holds the value greater than 'x'
    if (temp != NULL && temp->data > x) {
        *head_ref = temp->next; // Changed head
        free(temp); // free old head
        temp = *head_ref; // Change temp
    }
   
    // Delete occurrences other than head
    while (temp != NULL) {
   
        // Search for the node to be deleted,
        // keep track of the previous node as we
        // need to change 'prev->next'
        while (temp != NULL && temp->data <= x) {
            prev = temp;
            temp = temp->next;
        }
   
        // If required value node was not present
        // in linked list
        if (temp == NULL)
            return;
   
        // Unlink the node from linked list
        prev->next = temp->next;
   
        delete temp; // Free memory
   
        // Update Temp for next iteration of
        // outer loop
        temp = prev->next;
    }
}
   
// function to a print a linked list
void printList(Node* head)
{
    while (head) {
        cout << head->data << " ";
        head = head->next;
    }
}
   
// Driver program to test above
int main()
{
    // Create list: 7->3->4->8->5->1
    Node* head = getNode(7);
    head->next = getNode(3);
    head->next->next = getNode(4);
    head->next->next->next = getNode(8);
    head->next->next->next->next = getNode(5);
    head->next->next->next->next->next = getNode(1);
   
    int x = 6;
   
    cout << "Original List: ";
    printList(head);
   
    deleteGreaterNodes(&head, x);
   
    cout << "\nModified List: ";
    printList(head);
   
    return 0;
}

Java

// Java implementation to delete all nodes from the list
// that are greater than the specified value x
import java.io.*;
 
class Node {
    int data;
    Node next;
}
 
class GFG {
 
    // Function to get a new node.
    public Node getNode(int data)
    {
        Node new_node = new Node();
        new_node.data = data;
        new_node.next = null;
        return new_node;
    }
 
    // Function to print linked list.
    public void printList(Node head)
    {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
    }
 
    // Functions to delete nodes which have greater value
    // than x.
    public Node deleteGreaterNodes(Node head, int x)
    {
        Node temp = head;
       
        // while loop takes care if head node value greater
        // than x.
        while (temp != null && temp.data > x) {
            temp = temp.next;
            head = temp; // new head.
        }
        temp = head;
        Node prev = temp;
       
        // nodes other than head having value greater than x
        while (temp != null) {
            while (temp != null && temp.data <= x) {
                prev = temp;
                temp = temp.next;
            }
            if (temp == null) {
                return head;
            }
            // if there is a node in middle which has
            // greater value, we point the node to the next
            // node.
            prev.next = temp.next;
            // update temp for next iteration of loop.
            temp = prev.next;
        }
        return head;
    }
 
    public static void main(String[] args)
    {
 
        GFG list = new GFG();
 
        // Create list: 7->3->4->8->5->1.
        Node head = list.getNode(7);
        head.next = list.getNode(3);
        head.next.next = list.getNode(4);
        head.next.next.next = list.getNode(8);
        head.next.next.next.next = list.getNode(5);
        head.next.next.next.next.next = list.getNode(1);
 
        System.out.print("Original List: ");
        list.printList(head);
 
        int x = 6;
 
        head = list.deleteGreaterNodes(head, x);
        System.out.print("\nModified List: ");
        list.printList(head);
    }
}
 
// This code is contributed by lokesh (lokeshmvs21).

Producción:

Original List: 7 3 4 8 5 1 
Modified List: 3 4 5 1

Complejidad temporal: O(n).

Publicación traducida automáticamente

Artículo escrito por ayushjauhari14 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *