Algorithm
Convert LinkedList to Array:
-
Initialize Variables:
- Create an empty array.
- Obtain the size of the LinkedList.
-
Create Array:
- Create an array of the appropriate type and size.
-
Iterate and Copy:
- Iterate through each element in the LinkedList.
- Copy each element to the corresponding index in the array.
-
Result:
- The array now contains the elements of the LinkedList.
Convert Array to LinkedList:
-
Initialize Variables:
- Create an empty LinkedList.
-
Iterate and Add:
- Iterate through each element in the array.
- Add each element to the LinkedList.
-
Result:
- The LinkedList now contains the elements of the array.
Code Examples
#1 Code Example- Convert the LinkedList into Array
Code -
Java Programming
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
LinkedList < String> languages= new LinkedList<>();
// Add elements in the linked list
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
System.out.println("LinkedList: " + languages);
// Create a new array of String type
String[] arr = new String[languages.size()];
// Convert LinkedList into the string array
languages.toArray(arr);
System.out.print("Array: ");
for(String item:arr) {
System.out.print(item+", ");
}
}
}
Copy The Code &
Try With Live Editor
Output
LinkedList: [Java, Python, JavaScript]
Array: Java, Python, JavaScript,
Array: Java, Python, JavaScript,
#2 Code Example- Convert Array to LinkedList
Code -
Java Programming
import java.util.Arrays;
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
// create an array
String[] array = {"Java", "Python", "C"};
System.out.println("Array: " + Arrays.toString(array));
// convert array to a linked list
LinkedList < String> languages= new LinkedList<>(Arrays.asList(array));
System.out.println("LinkedList: " + languages);
}
}
Copy The Code &
Try With Live Editor
Output
Array: [Java, Python, C]
LinkedList: [Java, Python, C]
LinkedList: [Java, Python, C]
Demonstration
Java Programing Example to Convert the LinkedList into an Array and vice versa-DevsEnv