Encuentre elementos mínimos y máximos en una lista enlazada circular individual

Dada una lista enlazada de  N      Nodes circulares simples. La tarea es encontrar los elementos más pequeños y más grandes en la lista circular enlazada.

Ejemplos :  

Input : List = 99->11->22->33->44->55->66
Output : Minimum = 11, Maximum = 99

Input : List = 12->11->9->33->125->6->99
Output : Minimum = 6, Maximum = 125 

La idea es recorrer la lista enlazada circular mientras no se alcanza el último Node e inicializar las variables max y min en INT_MIN e INT_MAX respectivamente. Después de eso, verifique la condición de que si el valor máximo es menor que el valor de la cabeza, entonces el valor de la cabeza se asigna al máximo o si el valor mínimo es mayor que el valor de la cabeza, entonces el valor de la cabeza se asigna al mínimo, de lo contrario la cabeza apunta al siguiente Node. Continúe este proceso hasta el último Node.

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ program to find minimum and maximum
// value from singly circular linked list
#include <bits/stdc++.h>
using namespace std;
 
// structure for a node
struct Node {
    int data;
    struct Node* next;
};
 
// Function to print minimum and maximum
// nodes of the circular linked list
void printMinMax(struct Node** head)
{
    // check list is empty
    if (*head == NULL) {
        return;
    }
 
    // pointer for traversing
    struct Node* current;
 
    // initialize head to current pointer
    current = *head;
 
    // initialize max int value to min
    // initialize min int value to max
    int min = INT_MAX, max = INT_MIN;
 
    // While last node is not reached
    do {
 
        // If current node data is lesser for min
        // then replace it
        if (current->data < min) {
            min = current->data;
        }
 
        // If current node data is greater for max
        // then replace it
        if (current->data > max) {
            max = current->data;
        }
 
        current = current->next;
    }while(current != head);
 
    cout << "\nMinimum = " << min << ", Maximum = " << max;
}
 
// Function to insert a node at the end of
// a Circular linked list
void insertNode(struct Node** head, int data)
{
    struct Node* current = *head;
    // Create a new node
    struct Node* newNode = new Node;
 
    // check node is created or not
    if (!newNode) {
        printf("\nMemory Error\n");
        return;
    }
 
    // insert data into newly created node
    newNode->data = data;
 
    // check list is empty
    // if not have any node then
    // make first node it
    if (*head == NULL) {
        newNode->next = newNode;
        *head = newNode;
        return;
    }
 
    // if list have already some node
    else {
 
        // move first node to last node
        while (current->next != *head) {
            current = current->next;
        }
 
        // put first or head node address
        // in new node link
        newNode->next = *head;
 
        // put new node address into
        // last node link(next)
        current->next = newNode;
    }
}
 
// Function to print the Circular linked list
void displayList(struct Node* head)
{
 
    struct Node* current = head;
 
    // if list is empty simply show message
    if (head == NULL) {
        printf("\nDisplay List is empty\n");
        return;
    }
 
    // traverse first to last node
    else {
        do {
            printf("%d ", current->data);
            current = current->next;
        } while (current != head);
    }
}
 
// Driver Code
int main()
{
    struct Node* Head = NULL;
 
    insertNode(&Head, 99);
    insertNode(&Head, 11);
    insertNode(&Head, 22);
    insertNode(&Head, 33);
    insertNode(&Head, 44);
    insertNode(&Head, 55);
    insertNode(&Head, 66);
 
    cout << "Initial List: ";
 
    displayList(Head);
 
    printMinMax(&Head);
 
    return 0;
}

Java

// Java program to find minimum and maximum
// value from singly circular linked list
class GFG
{
 
// structure for a node
static class Node
{
    int data;
    Node next;
};
 
// Function to print minimum and maximum
// nodes of the circular linked list
static void printMinMax(Node head)
{
    // check list is empty
    if (head == null)
    {
        return;
    }
 
    // pointer for traversing
    Node current;
 
    // initialize head to current pointer
    current = head;
 
    // initialize max int value to min
    // initialize min int value to max
    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
 
    // While last node is not reached
    while (current.next != head)
    {
 
        // If current node data is lesser for min
        // then replace it
        if (current.data < min)
        {
            min = current.data;
        }
 
        // If current node data is greater for max
        // then replace it
        if (current.data > max)
        {
            max = current.data;
        }
 
        current = current.next;
    }
 
    System.out.println( "\nMinimum = " + min + ", Maximum = " + max);
}
 
// Function to insert a node at the end of
// a Circular linked list
static Node insertNode(Node head, int data)
{
    Node current = head;
     
    // Create a new node
    Node newNode = new Node();
 
    // check node is created or not
    if (newNode == null)
    {
        System.out.printf("\nMemory Error\n");
        return null;
    }
 
    // insert data into newly created node
    newNode.data = data;
 
    // check list is empty
    // if not have any node then
    // make first node it
    if (head == null)
    {
        newNode.next = newNode;
        head = newNode;
        return head;
    }
 
    // if list have already some node
    else
    {
 
        // move first node to last node
        while (current.next != head)
        {
            current = current.next;
        }
 
        // put first or head node address
        // in new node link
        newNode.next = head;
 
        // put new node address into
        // last node link(next)
        current.next = newNode;
    }
    return head;
}
 
// Function to print the Circular linked list
static void displayList(Node head)
{
 
    Node current = head;
 
    // if list is empty simply show message
    if (head == null)
    {
        System.out.printf("\nDisplay List is empty\n");
        return;
    }
 
    // traverse first to last node
    else
    {
        do
        {
            System.out.printf("%d ", current.data);
            current = current.next;
        } while (current != head);
    }
}
 
// Driver Code
public static void main(String args[])
{
    Node Head = null;
 
    Head=insertNode(Head, 99);
    Head=insertNode(Head, 11);
    Head=insertNode(Head, 22);
    Head=insertNode(Head, 33);
    Head=insertNode(Head, 44);
    Head=insertNode(Head, 55);
    Head=insertNode(Head, 66);
 
    System.out.println("Initial List: ");
 
    displayList(Head);
 
    printMinMax(Head);
}
}
 
// This code is contributed by Arnab Kundu

Python3

# Python3 program to find minimum and maximum
# value from singly circular linked list
  
# structure for a node
class Node:
     
    def __init__(self):
         
        self.data = 0
        self.next = None
     
# Function to print minimum and maximum
# nodes of the circular linked list
def printMinMax(head):
 
    # check list is empty
    if (head == None):
        return;
  
    # initialize head to current pointer
    current = head;
  
    # initialize max int value to min
    # initialize min int value to max
    min = 1000000000
    max = -1000000000;
  
    # While last node is not reached
    while True:
  
        # If current node data is lesser for min
        # then replace it
        if (current.data < min):
            min = current.data;
  
        # If current node data is greater for max
        # then replace it
        if (current.data > max):
            max = current.data;
  
        current = current.next;       
        if(current == head):
            break   
    print('Minimum = {}, Maximum = {}'.format(min, max))
  
# Function to insert a node at the end of
# a Circular linked list
def insertNode(head, data):
    current = head;
     
    # Create a new node
    newNode = Node()
  
    # check node is created or not
    if not newNode:
        print("\nMemory Error");
        return head
  
    # insert data into newly created node
    newNode.data = data;
  
    # check list is empty
    # if not have any node then
    # make first node it
    if (head == None):
        newNode.next = newNode;
        head = newNode;
        return head
  
    # if list have already some node
    else:
  
        # move first node to last node
        while (current.next != head):
            current = current.next;
  
        # put first or head node address
        # in new node link
        newNode.next = head;
  
        # put new node address into
        # last node link(next)
        current.next = newNode;       
    return head
  
# Function to print the Circular linked list
def displayList(head):
    current = head;
  
    # if list is empty simply show message
    if (head == None):
        print("\nDisplay List is empty");
        return;
  
    # traverse first to last node
    else:
         
        while True:
            print(current.data, end=' ');
            current = current.next;          
            if(current==head):
                break
    print()
  
# Driver Code
if __name__=='__main__':
     
    Head = None;
  
    Head = insertNode(Head, 99);
    Head = insertNode(Head, 11);
    Head = insertNode(Head, 22);
    Head = insertNode(Head, 33);
    Head = insertNode(Head, 44);
    Head = insertNode(Head, 55);
    Head = insertNode(Head, 66);
  
    print("Initial List: ", end = '')
  
    displayList(Head);
  
    printMinMax(Head);
  
# This code is contributed by rutvik_56

C#

// C# program to find minimum and maximum
// value from singly circular linked list
using System;
     
class GFG
{
 
// structure for a node
public class Node
{
    public int data;
    public Node next;
};
 
// Function to print minimum and maximum
// nodes of the circular linked list
static void printMinMax(Node head)
{
    // check list is empty
    if (head == null)
    {
        return;
    }
 
    // pointer for traversing
    Node current;
 
    // initialize head to current pointer
    current = head;
 
    // initialize max int value to min
    // initialize min int value to max
    int min = int.MaxValue, max = int.MinValue;
 
    // While last node is not reached
    while (current.next != head)
    {
 
        // If current node data is lesser for min
        // then replace it
        if (current.data < min)
        {
            min = current.data;
        }
 
        // If current node data is greater for max
        // then replace it
        if (current.data > max)
        {
            max = current.data;
        }
 
        current = current.next;
    }
 
    Console.WriteLine( "\nMinimum = " + min + ", Maximum = " + max);
}
 
// Function to insert a node at the end of
// a Circular linked list
static Node insertNode(Node head, int data)
{
    Node current = head;
     
    // Create a new node
    Node newNode = new Node();
 
    // check node is created or not
    if (newNode == null)
    {
        Console.Write("\nMemory Error\n");
        return null;
    }
 
    // insert data into newly created node
    newNode.data = data;
 
    // check list is empty
    // if not have any node then
    // make first node it
    if (head == null)
    {
        newNode.next = newNode;
        head = newNode;
        return head;
    }
 
    // if list have already some node
    else
    {
 
        // move first node to last node
        while (current.next != head)
        {
            current = current.next;
        }
 
        // put first or head node address
        // in new node link
        newNode.next = head;
 
        // put new node address into
        // last node link(next)
        current.next = newNode;
    }
    return head;
}
 
// Function to print the Circular linked list
static void displayList(Node head)
{
 
    Node current = head;
 
    // if list is empty simply show message
    if (head == null)
    {
        Console.Write("\nDisplay List is empty\n");
        return;
    }
 
    // traverse first to last node
    else
    {
        do
        {
            Console.Write("{0} ", current.data);
            current = current.next;
        } while (current != head);
    }
}
 
// Driver Code
public static void Main()
{
    Node Head = null;
 
    Head=insertNode(Head, 99);
    Head=insertNode(Head, 11);
    Head=insertNode(Head, 22);
    Head=insertNode(Head, 33);
    Head=insertNode(Head, 44);
    Head=insertNode(Head, 55);
    Head=insertNode(Head, 66);
 
    Console.WriteLine("Initial List: ");
 
    displayList(Head);
 
    printMinMax(Head);
}
}
 
/* This code contributed by PrinciRaj1992 */

Javascript

<script>
// javascript program to find minimum and maximum
// value from singly circular linked list    
// structure for a node
class Node {
    constructor() {
        this.data = 0;
        this.next = null;
    }
}
 
// Function to print minimum and maximum
// nodes of the circular linked list
function printMinMax(head) {
    // check list is empty
    if (head == null) {
        return;
    }
 
    // pointer for traversing
    var current;
 
    // initialize head to current pointer
    current = head;
 
    // initialize max var value to min
    // initialize min var value to max
    var min = Number.MAX_VALUE, max = Number.MIN_VALUE;
 
    // While last node is not reached
    while (current.next != head) {
 
        // If current node data is lesser for min
        // then replace it
        if (current.data < min) {
            min = current.data;
        }
 
        // If current node data is greater for max
        // then replace it
        if (current.data > max) {
            max = current.data;
        }
 
        current = current.next;
    }
 
    document.write("<br/>Minimum = " + min + ", Maximum = " + max);
}
 
// Function to insert a node at the end of
// a Circular linked list
function insertNode(head , data) {
    var current = head;
 
    // Create a new node
    var newNode = new Node();
 
    // check node is created or not
    if (newNode == null) {
        document.write("<br/>Memory Error\n");
        return null;
    }
 
    // insert data into newly created node
    newNode.data = data;
 
    // check list is empty
    // if not have any node then
    // make first node it
    if (head == null) {
        newNode.next = newNode;
        head = newNode;
        return head;
    }
 
    // if list have already some node
    else {
 
        // move first node to last node
        while (current.next != head) {
            current = current.next;
        }
 
        // put first or head node address
        // in new node link
        newNode.next = head;
 
        // put new node address into
        // last node link(next)
        current.next = newNode;
    }
    return head;
}
 
// Function to print the Circular linked list
function displayList(head) {
 
    var current = head;
 
    // if list is empty simply show message
    if (head == null) {
        document.write("<br/>Display List is empty<br/>");
        return;
    }
 
    // traverse first to last node
    else {
        do {
            document.write(current.data+" ");
            current = current.next;
        } while (current != head);
    }
}
 
// Driver Code
     
var Head = null;
 
Head = insertNode(Head, 99);
Head = insertNode(Head, 11);
Head = insertNode(Head, 22);
Head = insertNode(Head, 33);
Head = insertNode(Head, 44);
Head = insertNode(Head, 55);
Head = insertNode(Head, 66);
   
document.write("Initial List: ");
 
displayList(Head);
 
printMinMax(Head);
 
// This code contributed by umadevi9616
</script>
Producción: 

Initial List: 99 11 22 33 44 55 66 
Minimum = 11, Maximum = 99

 

Complejidad de tiempo: O (n), ya que estamos usando un bucle para atravesar n veces. Donde n es el número de Nodes en la lista enlazada.

Espacio auxiliar: O(1), ya que no estamos utilizando ningún espacio adicional.

Publicación traducida automáticamente

Artículo escrito por Rajput-Ji 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 *