Create linked list from a given array
Last Updated :
01 Aug, 2024
Given an array arr[] of size N. The task is to create linked list from the given array.
Examples:
Input : arr[] = {1, 2, 3, 4, 5}
Output : 1->2->3->4->5
Input :arr[] = {10, 11, 12, 13, 14}
Output : 10->11->12->13->14
Simple Approach: For each element of an array arr[] we create a node in a linked list and insert it at the end.
C++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int d)
{
data = d;
next = NULL;
}
};
// Function to insert node at the end
Node* insertEnd(Node* root, int item)
{
Node* temp = new Node(item);
if (root == NULL)
return temp;
Node* last = root;
while (last->next != NULL) {
last = last->next;
}
last->next = temp;
return root;
}
Node* arrayToList(int arr[], int n)
{
Node* root = NULL;
for (int i = 0; i < n; i++) {
root = insertEnd(root, arr[i]);
}
return root;
}
void display(Node* root)
{
while (root != NULL) {
cout << root->data << " ";
root = root->next;
}
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
Node* root = arrayToList(arr, n);
display(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert node at the end
struct Node* insertEnd(struct Node* root, int item) {
struct Node* temp = createNode(item);
if (root == NULL)
return temp;
struct Node* last = root;
while (last->next != NULL)
last = last->next;
last->next = temp;
return root;
}
struct Node* arrayToList(int arr[], int n) {
struct Node* root = NULL;
for (int i = 0; i < n; i++) {
root = insertEnd(root, arr[i]);
}
return root;
}
void display(struct Node* root) {
while (root != NULL) {
printf("%d ", root->data);
root = root->next;
}
}
// Driver code
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
struct Node* root = arrayToList(arr, n);
display(root);
return 0;
}
Java
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class GfG {
public static Node insertEnd(Node root, int item) {
Node temp = new Node(item);
if (root == null) {
return temp;
}
Node last = root;
while (last.next != null) {
last = last.next;
}
last.next = temp;
return root;
}
public static Node arrayToList(int[] arr) {
Node root = null;
for (int i = 0; i < arr.length; i++) {
root = insertEnd(root, arr[i]);
}
return root;
}
public static void display(Node root) {
while (root != null) {
System.out.print(root.data + " ");
root = root.next;
}
}
// Driver code
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
Node root = arrayToList(arr);
display(root);
}
}
Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def insert_end(root, item):
temp = Node(item)
if root is None:
return temp
last = root
while last.next is not None:
last = last.next
last.next = temp
return root
def array_to_list(arr):
root = None
for item in arr:
root = insert_end(root, item)
return root
def display(root):
while root is not None:
print(root.data, end=" ")
root = root.next
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5]
root = array_to_list(arr)
display(root)
C#
using System;
class Node {
public int data;
public Node next;
public Node(int d) {
data = d;
next = null;
}
}
class GfG {
public static Node InsertEnd(Node root, int item) {
Node temp = new Node(item);
if (root == null) {
return temp;
}
Node last = root;
while (last.next != null) {
last = last.next;
}
last.next = temp;
return root;
}
public static Node ArrayToList(int[] arr) {
Node root = null;
for (int i = 0; i < arr.Length; i++) {
root = InsertEnd(root, arr[i]);
}
return root;
}
public static void Display(Node root) {
while (root != null) {
Console.Write(root.data + " ");
root = root.next;
}
}
// Driver code
public static void Main(string[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
Node root = ArrayToList(arr);
Display(root);
}
}
JavaScript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
function insertEnd(root, item) {
const temp = new Node(item);
if (root === null) {
return temp;
}
let last = root;
while (last.next !== null) {
last = last.next;
}
last.next = temp;
return root;
}
function arrayToList(arr) {
let root = null;
for (let i = 0; i < arr.length; i++) {
root = insertEnd(root, arr[i]);
}
return root;
}
function display(root) {
while (root !== null) {
process.stdout.write(root.data + " ");
root = root.next;
}
}
// Example usage
const arr = [1, 2, 3, 4, 5];
const root = arrayToList(arr);
display(root);
Time Complexity : O(n*n)
Efficient Approach: We traverse array from end and insert every element at the beginning of the list.
C++
#include <iostream>
using namespace std;
// Representation of a node
struct Node {
int data;
Node* next;
Node(int d){
data = d;
next = NULL;
}
};
// Function to insert node
void insert(Node** root, int item)
{
Node* temp = new Node(item);
temp->next = *root;
*root = temp;
}
void display(Node* root)
{
while (root != NULL) {
cout << root->data << " ";
root = root->next;
}
}
Node *arrayToList(int arr[], int n)
{
Node *root = NULL;
for (int i = n-1; i >= 0 ; i--)
insert(&root, arr[i]);
return root;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
Node* root = arrayToList(arr, n);
display(root);
return 0;
}
Java
// Java program to print level order traversal
// in spiral form using one queue and one stack.
import java.util.*;
class GFG
{
// Representation of a node
static class Node
{
int data;
Node next;
Node (int d) {
data = d;
next = null;
}
};
static Node root;
// Function to insert node
static Node insert(Node root, int item)
{
Node temp = new Node(item);
temp.next = root;
root = temp;
return root;
}
static void display(Node root)
{
while (root != null)
{
System.out.print(root.data + " ");
root = root.next;
}
}
static Node arrayToList(int arr[], int n)
{
root = null;
for (int i = n - 1; i >= 0 ; i--)
root = insert(root, arr[i]);
return root;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = arr.length;
Node root = arrayToList(arr, n);
display(root);
}
}
Python
# Python3 program to print level order traversal
# in spiral form using one queue and one stack.
# Representation of a Node
class Node:
def __init__(self, data):
self.data = data
self.next = next
# Function to insert Node
def insert(root, item):
temp = Node(0)
temp.data = item
temp.next = root
root = temp
return root
def display(root):
while (root != None):
print(root.data, end=" ")
root = root.next
def arrayToList(arr, n):
root = None
for i in range(n - 1, -1, -1):
root = insert(root, arr[i])
return root
# Driver code
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5];
n = len(arr)
root = arrayToList(arr, n);
display(root)
# This code is contributed by 29AjayKumar
C#
// C# program to print level order traversal
// in spiral form using one queue and one stack.
using System;
class GFG
{
// Representation of a node
public class Node
{
public int data;
public Node next;
};
static Node root;
// Function to insert node
static Node insert(Node root, int item)
{
Node temp = new Node();
temp.data = item;
temp.next = root;
root = temp;
return root;
}
static void display(Node root)
{
while (root != null)
{
Console.Write(root.data + " ");
root = root.next;
}
}
static Node arrayToList(int []arr, int n)
{
root = null;
for (int i = n - 1; i >= 0 ; i--)
root = insert(root, arr[i]);
return root;
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
Node root = arrayToList(arr, n);
display(root);
}
}
// This code is contributed by Rajput-Ji
JavaScript
// JavaScript program to print level order traversal
// in spiral form using one queue and one stack.
// Representation of a node
class Node {
constructor()
{
this.data = 0;
this.next = null;
}
}
var root;
// Function to insert node
function insert(root, item)
{
var temp = new Node();
temp.data = item;
temp.next = root;
root = temp;
return root;
}
function display(root)
{
while (root != null) {
console.log(root.data + " ");
root = root.next;
}
}
function arrayToList(arr, n)
{
root = null;
for (var i = n - 1; i >= 0; i--)
root = insert(root, arr[i]);
return root;
}
// Driver code
var arr = [ 1, 2, 3, 4, 5 ];
var n = arr.length;
var root = arrayToList(arr, n);
display(root);
Time Complexity : O(n)
Alternate Efficient Solution is maintain tail pointer, traverse array elements from left to right, insert at tail and update tail after insertion.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read