Dada una lista enlazada simple. La tarea es encontrar el promedio de todos los Nodes de la lista enlazada simple dada .
Ejemplos :
Input: 7->6->8->4->1 Output: 26 Average of nodes: (7 + 6 + 8 + 4 + 1 ) / 5 = 5.2 Input: 1->7->3->9->11->5 Output: 6
Solución iterativa:
- Inicialice un puntero ptr con el encabezado de la lista enlazada y una variable de suma con 0.
- Comience a recorrer la lista vinculada utilizando un bucle hasta que se atraviesen todos los Nodes.
- Agregue el valor del Node actual a la suma, es decir, suma += ptr -> datos.
- Incremente el puntero al siguiente Node de la lista enlazada, es decir, ptr = ptr ->next.
- Divide la suma por el número total de Nodes y devuelve el promedio.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation to find the average of // nodes of the Linked List #include <bits/stdc++.h> using namespace std; /* A Linked list node */ struct Node { int data; struct Node* next; }; // function to insert a node at the // beginning of the linked list void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // Function to iteratively find the avg of // nodes of the given linked list float avgOfNodes(struct Node* head) { // if head = NULL if (!head) return -1; int count = 0; // Initialize count int sum = 0; float avg = 0.0; struct Node* current = head; // Initialize current while (current != NULL) { count++; sum += current->data; current = current->next; } // calculate average avg = (double)sum / count; return avg; } // Driver Code int main() { struct Node* head = NULL; // create linked list 7->6->8->4->1 push(&head, 7); push(&head, 6); push(&head, 8); push(&head, 4); push(&head, 1); cout << "Average of nodes = " << avgOfNodes(head); return 0; }
Java
// Java implementation to find the average of // nodes of the Linked List class GFG { /* A Linked list node */ static class Node { int data; Node next; }; // function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } // Function to iteratively find the avg of // nodes of the given linked list static double avgOfNodes(Node head) { // if head = null if (head == null) return -1; int count = 0; // Initialize count int sum = 0; double avg = 0.0; Node current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = (double)sum / count; return avg; } // Driver Code public static void main(String args[]) { Node head = null; // create linked list 7.6.8.4.1 head=push(head, 7); head=push(head, 6); head=push(head, 8); head=push(head, 4); head=push(head, 1); System.out.println("Average of nodes = " + avgOfNodes(head)); } } // This code is contributed by Arnab Kundu
Python3
# Python3 implementation to find the average of # nodes of the Linked List class newNode: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None # function to insert a node at the # beginning of the linked list def push(node,data): ''' allocate node ''' if (node == None): return (newNode(data)) else: node.next = push(node.next, data) return node # Function to iteratively find the avg of # nodes of the given linked list def avgOfNodes(head): # if head = NULL if (head == None): return -1 count = 0 # Initialize count sum = 0 avg = 0.0 while (head != None): count += 1 sum += head.data head = head.next # calculate average avg = sum / count return avg # Driver Code # create linked list 7.6.8.4.1 head = newNode(7) push(head, 6) push(head, 8) push(head, 4) push(head, 1) print("Average of nodes = ",avgOfNodes(head)) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10)
C#
// C# implementation to find the average // of nodes of the Linked List using System; class GFG { /* A Linked list node */ public class Node { public int data; public Node next; }; // function to insert a node at the // beginning of the linked list static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } // Function to iteratively find the avg of // nodes of the given linked list static double avgOfNodes(Node head) { // if head = null if (head == null) return -1; int count = 0; // Initialize count int sum = 0; double avg = 0.0; Node current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = (double)sum / count; return avg; } // Driver Code public static void Main(String []args) { Node head = null; // create linked list 7.6.8.4.1 head=push(head, 7); head=push(head, 6); head=push(head, 8); head=push(head, 4); head=push(head, 1); Console.WriteLine("Average of nodes = " + avgOfNodes(head)); } } // This code is contributed by Rajput-Ji
Javascript
<script> // javascript implementation to find the average of // nodes of the Linked List /* A Linked list node */ class Node { constructor(val) { this.data = val; this.next = null; } } // function to insert a node at the // beginning of the linked list function push(head_ref , new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } // Function to iteratively find the avg of // nodes of the given linked list function avgOfNodes(head) { // if head = null if (head == null) return -1; var count = 0; // Initialize count var sum = 0; var avg = 0.0; var current = head; // Initialize current while (current != null) { count++; sum += current.data; current = current.next; } // calculate average avg = sum / count; return avg; } // Driver Code var head = null; // create linked list 7.6.8.4.1 head = push(head, 7); head = push(head, 6); head = push(head, 8); head = push(head, 4); head = push(head, 1); document.write("Average of nodes = " + avgOfNodes(head)); // This code contributed by aashish1995 </script>
Producción:
Average of nodes = 5.2
Complejidad temporal: O(n)
Donde n es igual al número de Nodes.
Publicación traducida automáticamente
Artículo escrito por VishalBachchas y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA