Create LinkedList from an array in Java
Hi coders! In this tutorial, we are going to learn how to create LinkedList from an array in Java, the combination of two data structures that are array and LinkedList.
Our task is to create a LinkedList from the elements of an array. As we know both array and LinkedList are linear data structures, the basic difference between these two is that LinkedList is a data structure in which each node has the reference of the next node whereas array works on index basis.
Now the approach to create LinkedList from an array elements, we have to traverse the array one by one and simultaneously create the node with that element.
Steps to create LinkedList from an array:
- Start traversing the array elements one by one from the end and simultaneously create node from that element.
- Now move the head node to point to the next of current.
- After traversing the whole array the head node will point to the very first element of array.
- Call the function to display the created LinkedList.
You may also learn: How to merge two linked lists in Java
Code to create LinkedList from an array in Java
import java.util.*; class Codespeedy { // Node static class Node { int data; Node next; } //head of LinkedList static Node head; // Function to insert node static Node insert(Node head, int arrayElement) { Node newNode = new Node(); newNode.data = arrayElement; newNode.next = head; head = newNode; return head; } static void displayList(Node head) { while (head != null) { System.out.print(root.data + " "); head = head.next; } } static Node arrayToLinkedList(int arr[], int n) { head = null; for (int i = n - 1; i >= 0 ; i--) head = insert(head, arr[i]); return head; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 6, 8, 9}; int n = arr.length; Node head = arrayToLinkedList(arr, n); displayList(head); } } //Code is provided by Anubhav Srivastava
Output: 1->2->3->6->8->9
How to use Linked List In Java Without Using Collection Class
Time complexity
Hence, the time complexity of the code is O(n)
I hope you like the solution.
On line number 27 it should be head not root change it please