Comprobar si la suma de los elementos de un Node es igual al valor clave dado

Dado un entero k y una lista enlazada, cada Node consta de un par de variables enteras primero y segundo para contener los datos, y un puntero que apunta al siguiente Node en la lista. La tarea es encontrar si la suma de las variables de datos de cualquiera de los Nodes es igual a k . En caso afirmativo, escriba , de lo contrario, escriba No.

Ejemplos:  

Entrada: (1, 2) -> (2, 3) -> (3, 4) -> (4, 5) -> NULL, k = 5 
Salida: Sí 
Para el segundo Node, la suma de las variables de datos es 2 + 3 = 5.

Entrada: (1, 2) -> (2, 3) -> (3, 4) -> (4, 5) -> NULL, k = 15 
Salida: No 

Enfoque: recorrer toda la lista enlazada hasta que la suma de los elementos de un Node sea igual al valor clave. Cuando la suma del elemento de un Node es igual al valor clave, imprima . Si no existe tal Node cuya suma de elementos sea igual al valor de la clave, imprima  No.

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

C++

// C++ implementation of the approach
#include <iostream>
using namespace std;
 
// Represents node of the linked list
struct Node {
    int first;
    int second;
    Node* next;
};
 
// Insertion in linked list
void insert(Node** head, int f, int s)
{
    Node* ptr = *head;
    Node* temp = new Node();
    temp->first = f;
    temp->second = s;
    temp->next = NULL;
 
    if (*head == NULL)
        *head = temp;
    else {
        while (ptr->next != NULL)
            ptr = ptr->next;
 
        ptr->next = temp;
    }
}
 
// Function that returns true
// if the sum of element in a node = k
bool checkK(Node* head, int k)
{
 
    // Check every node of the linked list
    while (head != NULL) {
 
        // If sum of the data of the current node = k
        if ((head->first + head->second) == k)
            return true;
 
        // Get to next node in the list
        head = head->next;
    }
 
    // No matching node found
    return false;
}
// Driver code
int main()
{
    Node* head = NULL;
    insert(&head, 1, 2);
    insert(&head, 2, 3);
    insert(&head, 3, 4);
    insert(&head, 4, 5);
    int k = 5;
 
    if (checkK(head, k))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}

Java

// Java implementation of the approach
class GfG {
 
    // Represents node of the linked list
    static class Node {
        int first;
        int second;
        Node next;
    }
    static Node head = null;
 
    // Insertion in linked list
    static void insert(int f, int s)
    {
        Node ptr = head;
        Node temp = new Node();
        temp.first = f;
        temp.second = s;
        temp.next = null;
 
        if (head == null)
            head = temp;
        else {
            while (ptr.next != null)
                ptr = ptr.next;
 
            ptr.next = temp;
        }
    }
 
    // Function that returns true
    // if the sum of element in a node = k
    static boolean checkK(Node head, int k)
    {
 
        // Check every node of the linked list
        while (head != null) {
 
            // If sum of the data of the current node = k
            if ((head.first + head.second) == k)
                return true;
 
            // Get to next node in the list
            head = head.next;
        }
 
        // No matching node found
        return false;
    }
    // Driver code
    public static void main(String[] args)
    {
        // Node* head = NULL;
        insert(1, 2);
        insert(2, 3);
        insert(3, 4);
        insert(4, 5);
        int k = 5;
 
        if (checkK(head, k) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Prerna Saini

Python3

# Python3 implementation of the approach
  
# Represents node of the linked list
class Node:
     
    def __init__(self):
         
        self.first = 0
        self.second = 0
        self.next = None
 
# Insertion in linked list
def insert(head, f, s):
 
    ptr = head
    temp = Node()
    temp.first = f
    temp.second = s
    temp.next = None
  
    if (head == None):
        head = temp
    else:
        while (ptr.next != None):
            ptr = ptr.next
  
        ptr.next = temp
         
    return head
     
# Function that returns true
# if the sum of element in a node = k
def checkK(head, k):
 
    # Check every node of the linked list
    while (head != None):
  
        # If sum of the data of the current node = k
        if ((head.first + head.second) == k):
            return True
  
        # Get to next node in the list
        head = head.next
  
    # No matching node found
    return False
 
# Driver code
if __name__=='__main__':
     
    head = None
    head = insert(head, 1, 2)
    head = insert(head, 2, 3)
    head = insert(head, 3, 4)
    head = insert(head, 4, 5)
    k = 5
  
    if (checkK(head, k)):
        print("Yes")
    else:
        print("No")
  
# This code is contributed by rutvik_56

C#

using System;
 
// c# implementation of the approach
public class GfG {
 
    // Represents node of the linked list
    public class Node {
        public int first;
        public int second;
        public Node next;
    }
    public static Node head = null;
 
    // Insertion in linked list
    public static void insert(int f, int s)
    {
        Node ptr = head;
        Node temp = new Node();
        temp.first = f;
        temp.second = s;
        temp.next = null;
 
        if (head == null) {
            head = temp;
        }
        else {
            while (ptr.next != null) {
                ptr = ptr.next;
            }
 
            ptr.next = temp;
        }
    }
 
    // Function that returns true
    // if the sum of element in a node = k
    public static bool checkK(Node head, int k)
    {
 
        // Check every node of the linked list
        while (head != null) {
 
            // If sum of the data of the current node = k
            if ((head.first + head.second) == k) {
                return true;
            }
 
            // Get to next node in the list
            head = head.next;
        }
 
        // No matching node found
        return false;
    }
    // Driver code
    public static void Main(string[] args)
    {
        // Node* head = NULL;
        insert(1, 2);
        insert(2, 3);
        insert(3, 4);
        insert(4, 5);
        int k = 5;
 
        if (checkK(head, k) == true) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}

Javascript

<script>
 
// Javascript implementation of the approach
 
// Structure of a node of linked list
class Node {
        constructor() {
                this.first = 0;
                this.second = 0;
                this.next = null;
             }
        }
         
// Insertion in linked list
function insert( f,  s)
{
    var ptr = head;
    var temp = new Node();
    temp.first = f;
    temp.second = s;
    temp.next = null;
 
    if (head == null)
        head = temp;
    else {
        while (ptr.next != null)
            ptr = ptr.next;
 
        ptr.next = temp;
    }
}
 
// Function that returns true
// if the sum of element in a node = k
function checkK( head,  k)
{
 
    // Check every node of the linked list
    while (head != null) {
 
        // If sum of the data of the current node = k
        if ((head.first + head.second) == k)
            return true;
 
        // Get to next node in the list
        head = head.next;
    }
 
    // No matching node found
    return false;
}
 
// Driver Code
 
var head = null;
insert(1, 2);
insert(2, 3);
insert(3, 4);
insert(4, 5);
let k = 5;
 
if (checkK(head, k) == true)
    document.write("Yes");
else
    document.write("No");
 
// This code is contributed by jana_sayantn.
</script>
Producción: 

Yes

 

Publicación traducida automáticamente

Artículo escrito por Premdeep Toppo 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 *