Encuentre el Node balanceado en una lista enlazada

Dada una lista enlazada, la tarea es encontrar el Node equilibrado en una lista enlazada. Un Node balanceado es un Node donde la suma de todos los Nodes a su izquierda es igual a la suma de todos los Nodes a su derecha, si no se encuentra tal Node, imprima -1 .

Ejemplos:  

Entrada: 1 -> 2 -> 7 -> 10 -> 1 -> 6 -> 3 -> NULL 
Salida: 10  La
suma de los Nodes a la izquierda de 10 es 1 + 2 + 7 = 10 
Y, a la derecha de 10 es 1 + 6 + 3 = 10

Entrada: 1 -> 5 -> 5 -> 10 -> -3 -> NULL 
Salida: -1 

Acercarse:  

  • Primero, encuentre la suma total de todos los valores de los Nodes.
  • Ahora, recorra la lista enlazada una por una y, mientras la recorre, realice un seguimiento de la suma del valor de todos los Nodes anteriores y encuentre la suma del Node restante restando el valor del Node actual y la suma del valor de los Nodes anteriores de la suma total.
  • Compare ambas sumas, si son iguales, entonces el Node actual es el Node requerido; de lo contrario, imprima -1.

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

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a node of linked list
class Node {
public:
    int data;
    Node* next;
    Node(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};
  
// Push the new node to front of
// the linked list
Node* push(Node* head, int data)
{
      
    // Return new node as head if
    // head is empty
    if (head == NULL)
    {
        return new Node(data);
    }
    Node* temp = new Node(data);
    temp->next = head;
    head = temp;
    return head;
}
  
// Function to find the balanced node
int findBalancedNode(Node* head)
{
    int tsum = 0;
    Node* curr_node = head;
      
    // Traverse through all node
    // to find the total sum
    while (curr_node != NULL)
    {
        tsum += curr_node->data;
        curr_node = curr_node->next;
    }
  
    // Set current_sum and remaining
    // sum to zero
    int current_sum = 0;
    int remaining_sum = 0;
    curr_node = head;
  
    // Traversing the list to
    // check balanced node
    while (curr_node != NULL)
    {
        remaining_sum = tsum - (current_sum +
                               curr_node->data);
  
        // If sum of the nodes on the left and
        // the current node is equal to the sum
        // of the nodes on the right
        if (current_sum == remaining_sum)
        {
            return curr_node->data;
        }
        current_sum += curr_node->data;
        curr_node = curr_node->next;
    }
    return -1;
}
 
// Driver code
int main()
{
    Node* head = NULL;
    head = push(head, 3);
    head = push(head, 6);
    head = push(head, 1);
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 2);
    head = push(head, 1);
    cout << findBalancedNode(head);
    return 0;
}
 
// This code is contributed by divyehrabadiya07

Java

// Java implementation of the approach
class GFG{
     
// Structure of a node of linked list
static class Node
{
    int data;
    Node next;
     
    Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}
 
// Push the new node to front of
// the linked list
static Node push(Node head, int data)
{
     
    // Return new node as head if
    // head is empty
    if (head == null)
    {
        return new Node(data);
    }
    Node temp = new Node(data);
    temp.next = head;
    head = temp;
    return head;
}
 
// Function to find the balanced node
static int findBalancedNode(Node head)
{
    int tsum = 0;
    Node curr_node = head;
     
    // Traverse through all node
    // to find the total sum
    while (curr_node != null)
    {
        tsum += curr_node.data;
        curr_node = curr_node.next;
    }
 
    // Set current_sum and remaining
    // sum to zero
    int current_sum = 0;
    int remaining_sum = 0;
    curr_node = head;
 
    // Traversing the list to
    // check balanced node
    while (curr_node != null)
    {
        remaining_sum = tsum - (current_sum +
                               curr_node.data);
 
        // If sum of the nodes on the left and
        // the current node is equal to the sum
        // of the nodes on the right
        if (current_sum == remaining_sum)
        {
            return curr_node.data;
        }
        current_sum += curr_node.data;
        curr_node = curr_node.next;
    }
    return -1;
}
 
// Driver code
public static void main(String []args)
{
    Node head = null;
    head = push(head, 3);
    head = push(head, 6);
    head = push(head, 1);
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 2);
    head = push(head, 1);
 
    System.out.println(findBalancedNode(head));
}
}
 
// This code is contributed by rutvik_56

Python3

# Python3 implementation of the approach
import sys
import math
 
# Structure of a node of linked list
class Node:
    def __init__(self, data):
        self.next = None
        self.data = data
 
# Push the new node to front of the linked list
def push(head, data):
 
    # Return new node as head if head is empty
    if not head:
        return Node(data)
    temp = Node(data)
    temp.next = head
    head = temp
    return head
 
# Function to find the balanced node
def findBalancedNode(head):
    tsum = 0
    curr_node = head
     
    # Traverse through all node
    # to find the total sum
    while curr_node:
        tsum+= curr_node.data
        curr_node = curr_node.next
     
    # Set current_sum and remaining sum to zero
    current_sum, remaining_sum = 0, 0
    curr_node = head
 
    # Traversing the list to check balanced node
    while(curr_node):
        remaining_sum = tsum-(current_sum + curr_node.data)
 
        # If sum of the nodes on the left and the current node
        # is equal to the sum of the nodes on the right
        if current_sum == remaining_sum:
            return curr_node.data
        current_sum+= curr_node.data
        curr_node = curr_node.next
     
    return -1
 
# Driver code
if __name__=='__main__':
    head = None
    head = push(head, 3)
    head = push(head, 6)
    head = push(head, 1)
    head = push(head, 10)
    head = push(head, 7)
    head = push(head, 2)
    head = push(head, 1)
 
    print(findBalancedNode(head))

C#

// C# implementation of the approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
 
  // Structure of a node of linked list
  class Node
  {
    public int data;
    public Node next;
 
    public Node(int data)
    {
      this.data = data;
      this.next = null;
    }
  }
 
  // Push the new node to front of
  // the linked list
  static Node push(Node head, int data)
  {
 
    // Return new node as head if
    // head is empty
    if (head == null)
    {
      return new Node(data);
    }
    Node temp = new Node(data);
    temp.next = head;
    head = temp;
    return head;
  }
 
  // Function to find the balanced node
  static int findBalancedNode(Node head)
  {
    int tsum = 0;
    Node curr_node = head;
 
    // Traverse through all node
    // to find the total sum
    while (curr_node != null)
    {
      tsum += curr_node.data;
      curr_node = curr_node.next;
    }
 
    // Set current_sum and remaining
    // sum to zero
    int current_sum = 0;
    int remaining_sum = 0;
    curr_node = head;
 
    // Traversing the list to
    // check balanced node
    while (curr_node != null)
    {
      remaining_sum = tsum - (current_sum +
                              curr_node.data);
 
      // If sum of the nodes on the left and
      // the current node is equal to the sum
      // of the nodes on the right
      if (current_sum == remaining_sum)
      {
        return curr_node.data;
      }
      current_sum += curr_node.data;
      curr_node = curr_node.next;
    }
    return -1;
  }
 
  // Driver code
  public static void Main(string []args)
  {
    Node head = null;
    head = push(head, 3);
    head = push(head, 6);
    head = push(head, 1);
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 2);
    head = push(head, 1);
    Console.Write(findBalancedNode(head));
  }
}
 
// This code is contributed by pratham76

Javascript

<script>
 
// Javascript implementation of the approach
 
// Structure of a node of linked list
class Node {
        constructor(data) {
                this.data = data;
                this.next = null;
             }
        }
         
         
// Push the new node to front of
// the linked list
function push( head, data)
{
     
    // Return new node as head if
    // head is empty
    if (head == null)
    {
        return new Node(data);
    }
    var temp = new Node(data);
    temp.next = head;
    head = temp;
    return head;
}
 
// Function to find the balanced node
function findBalancedNode( head)
{
    let tsum = 0;
    let curr_node = head;
     
    // Traverse through all node
    // to find the total sum
    while (curr_node != null)
    {
        tsum += curr_node.data;
        curr_node = curr_node.next;
    }
 
    // Set current_sum and remaining
    // sum to zero
    let current_sum = 0;
    let remaining_sum = 0;
    curr_node = head;
 
    // Traversing the list to
    // check balanced node
    while (curr_node != null)
    {
        remaining_sum = tsum - (current_sum +
                            curr_node.data);
 
        // If sum of the nodes on the left and
        // the current node is equal to the sum
        // of the nodes on the right
        if (current_sum == remaining_sum)
        {
            return curr_node.data;
        }
        current_sum += curr_node.data;
        curr_node = curr_node.next;
    }
    return -1;
}
 
    // Driver Code
 
    var head = null;
    head = push(head, 3);
    head = push(head, 6);
    head = push(head, 1);
    head = push(head, 10);
    head = push(head, 7);
    head = push(head, 2);
    head = push(head, 1);
 
    document.write(findBalancedNode(head));
 
// This code is contributed by Jana_sayantan.
</script>
Producción: 

10

 

Complejidad temporal: O(n)
Espacio auxiliar: O(1) 
 

Publicación traducida automáticamente

Artículo escrito por Vikash Kumar 37 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 *