Convierta una lista enlazada individualmente en una array

Dada una lista enlazada individualmente y la tarea es convertirla en una array.
Ejemplos: 
 

Entrada: Lista = 1 -> 2 -> 3 -> 4 -> 5 -> NULL 
Salida: 1 2 3 4 5
Entrada: Lista = 10 -> 20 -> 30 -> 40 -> 50 -> NULL 
Salida: 10 20 30 40 50 
 

Enfoque: En este artículo se ha discutido un enfoque para crear una lista enlazada a partir de la array dada . Aquí, se discutirá un enfoque para convertir la lista enlazada dada en una array. 
 

  • Encuentre la longitud de la lista enlazada dada, digamos len .
  • Cree una array de tamaño len .
  • Recorra la lista enlazada dada y almacene los elementos en la array uno a la vez.

Complete Interview Preparation - GFG

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

C++

// C++ implementation of the approach
#include <iostream>
using namespace std;
  
// Singly Linked List structure
struct node {
    int data;
    node* next;
};
  
// Function to add a new node
// to the Linked List
node* add(int data)
{
    node* newnode = new node;
    newnode->data = data;
    newnode->next = NULL;
    return newnode;
}
  
// Function to print the array contents
void printArr(int a[], int n)
{
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
}
  
// Function to return the length
// of the Linked List
int findlength(node* head)
{
    node* curr = head;
    int cnt = 0;
    while (curr != NULL) {
        cnt++;
        curr = curr->next;
    }
    return cnt;
}
  
// Function to convert the
// Linked List to an array
void convertArr(node* head)
{
  
    // Find the length of the
    // given linked list
    int len = findlength(head);
  
    // Create an array of the
    // required length
    int arr[len];
  
    int index = 0;
    node* curr = head;
  
    // Traverse the Linked List and add the
    // elements to the array one by one
    while (curr != NULL) {
        arr[index++] = curr->data;
        curr = curr->next;
    }
  
    // Print the created array
    printArr(arr, len);
}
  
// Driver code
int main()
{
    node* head = NULL;
    head = add(1);
    head->next = add(2);
    head->next->next = add(3);
    head->next->next->next = add(4);
    head->next->next->next->next = add(5);
  
    convertArr(head);
  
    return 0;
}

Java

// Java implementation of the approach
class GFG
{
  
// Singly Linked List structure
static class node
{
    int data;
    node next;
}
  
// Function to add a new node
// to the Linked List
static node add(int data)
{
    node newnode = new node();
    newnode.data = data;
    newnode.next = null;
    return newnode;
}
  
// Function to print the array contents
static void printArr(int a[], int n)
{
    for (int i = 0; i < n; i++)
        System.out.print(a[i]+" ");
}
  
// Function to return the length
// of the Linked List
static int findlength(node head)
{
    node curr = head;
    int cnt = 0;
    while (curr != null)
    {
        cnt++;
        curr = curr.next;
    }
    return cnt;
}
  
// Function to convert the
// Linked List to an array
static void convertArr(node head)
{
  
    // Find the length of the
    // given linked list
    int len = findlength(head);
  
    // Create an array of the
    // required length
    int []arr = new int[len];
  
    int index = 0;
    node curr = head;
  
    // Traverse the Linked List and add the
    // elements to the array one by one
    while (curr != null) 
    {
        arr[index++] = curr.data;
        curr = curr.next;
    }
  
    // Print the created array
    printArr(arr, len);
}
  
// Driver code 
public static void main(String []args)
{
    node head = new node();
    head = add(1);
    head.next = add(2);
    head.next.next = add(3);
    head.next.next.next = add(4);
    head.next.next.next.next = add(5);
  
    convertArr(head);
}
}
  
// This code is contributed by Rajput-Ji

Python3

# Python3 implementation of the approach
  
# Structure of a Node 
class node: 
    def __init__(self, data): 
        self.data = data 
        self.next = None
  
# Function to add a new node
# to the Linked List
def add(data):
  
    newnode = node(0)
    newnode.data = data
    newnode.next = None
    return newnode
  
# Function to print the array contents
def printArr(a, n):
  
    i = 0
    while(i < n):
        print (a[i], end = " ")
        i = i + 1
  
# Function to return the length
# of the Linked List
def findlength( head):
  
    curr = head
    cnt = 0
    while (curr != None):
      
        cnt = cnt + 1
        curr = curr.next
      
    return cnt
  
# Function to convert the
# Linked List to an array
def convertArr(head):
  
    # Find the length of the
    # given linked list
    len1 = findlength(head)
  
    # Create an array of the
    # required length
    arr = []
  
    index = 0
    curr = head
  
    # Traverse the Linked List and add the
    # elements to the array one by one
    while (curr != None): 
        arr.append( curr.data)
        curr = curr.next
      
    # Print the created array
    printArr(arr, len1)
  
# Driver code 
head = node(0)
head = add(1)
head.next = add(2)
head.next.next = add(3)
head.next.next.next = add(4)
head.next.next.next.next = add(5)
convertArr(head)
  
# This code is contributed by Arnab kundu

C#

// C# implementation of the approach
using System;
                      
class GFG
{
  
// Singly Linked List structure
public class node
{
    public int data;
    public node next;
}
  
// Function to add a new node
// to the Linked List
static node add(int data)
{
    node newnode = new node();
    newnode.data = data;
    newnode.next = null;
    return newnode;
}
  
// Function to print the array contents
static void printArr(int []a, int n)
{
    for (int i = 0; i < n; i++)
        Console.Write(a[i] + " ");
}
  
// Function to return the length
// of the Linked List
static int findlength(node head)
{
    node curr = head;
    int cnt = 0;
    while (curr != null)
    {
        cnt++;
        curr = curr.next;
    }
    return cnt;
}
  
// Function to convert the
// Linked List to an array
static void convertArr(node head)
{
  
    // Find the length of the
    // given linked list
    int len = findlength(head);
  
    // Create an array of the
    // required length
    int []arr = new int[len];
  
    int index = 0;
    node curr = head;
  
    // Traverse the Linked List and add the
    // elements to the array one by one
    while (curr != null) 
    {
        arr[index++] = curr.data;
        curr = curr.next;
    }
  
    // Print the created array
    printArr(arr, len);
}
  
// Driver code 
public static void Main(String []args)
{
    node head = new node();
    head = add(1);
    head.next = add(2);
    head.next.next = add(3);
    head.next.next.next = add(4);
    head.next.next.next.next = add(5);
  
    convertArr(head);
}
}
  
// This code is contributed by 29AjayKumar

Javascript

<script>
  
// JavaScript implementation of the approach
  
// Singly Linked List structure
class node {
        constructor() {
                this.data = 0;
                this.next = null;
             }
        }
          
// Function to add a new node
// to the Linked List
function add( data)
{
    var newnode = new node();
    newnode.data = data;
    newnode.next = null;
    return newnode;
}
  
// Function to print the array contents
function printArr( a,  n)
{
    for (let i = 0; i < n; i++)
        document.write(a[i]+" ");
}
  
// Function to return the length
// of the Linked List
function findlength( head)
{
    var curr = head;
    let cnt = 0;
    while (curr != null)
    {
        cnt++;
        curr = curr.next;
    }
    return cnt;
}
  
// Function to convert the
// Linked List to an array
function convertArr( head)
{
  
    // Find the length of the
    // given linked list
    let len = findlength(head);
  
    // Create an array of the
    // required length
    let arr = new Array(len);
      
    let index = 0;
    var curr = head;
  
    // Traverse the Linked List and add the
    // elements to the array one by one
    while (curr != null)
    {
        arr[index++] = curr.data;
        curr = curr.next;
    }
  
    // Print the created array
    printArr(arr, len);
}
  
// Driver Code
  
var head = new node();
head = add(1);
head.next = add(2);
head.next.next = add(3);
head.next.next.next = add(4);
head.next.next.next.next = add(5);
  
convertArr(head);
      
</script>
Producción: 

1 2 3 4 5

 

Complejidad temporal: O(N)
Espacio auxiliar: O(N)

Publicación traducida automáticamente

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