In: Computer Science
In java write a method that will take an array and change it into a linkedlist and then display it in the main method
If you have any problem with the code feel free to comment.
Program
class LinkedList {
// head node
private Node head;
// inner node class
private class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
// method to convert array to linkedlist
public void arrayToLinkedList(int[] data) {
// head node points to first element
head = new Node(data[0]);
Node last = head;
// looping through the array
for (int i = 1; i < data.length; i++) {
// looping through the list
while (last.next != null)
last = last.next;
// adding element at the end
last.next = new Node(data[i]);
}
}
// for printing the linkedlist
public void printList() {
Node currentNode = head;
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
}
}
public class Test {
public static void main(String[] args) {
// testing the method
int[] ar = { 5, 9, 3, 7, 2 };
LinkedList llist = new LinkedList();
llist.arrayToLinkedList(ar);
llist.printList();
}
}
Output