In: Computer Science
In java we will need to create a method that takes the array {1,2,3,4,5} and returns the head reference to a linkedList. We will also need to display the linked list in out main method.
Code:
public class LinkedListDisplay {
public static void main(String[] args) {
LinkedListDisplay
listDisplay = new LinkedListDisplay();
Node head =
listDisplay
.generateLinkedList(new
int[]
{
1, 2,
3, 4,
5
});
// display the list.
Node temp = head;
while
(temp != null)
{
System.out.print(temp.item + "
");
temp = temp.next;
}
System.out.println();
}
private Node
generateLinkedList(int[]
elements) {
Node head =
new
Node(elements[0]);
Node temp = head;
for
(int i
= 1; i < elements.length; ++i) {
Node newNode = new Node(elements[i]);
temp.next = newNode;
temp = newNode;
}
return
head;
}
class Node {
int
item;
Node
next;
Node(int item) {
this.item = item;
}
}
}
Snapshot of the output:
Snapshot of the code:
Let me know if anything is not clear.