So I am making a linked list and in my insertion, I need to maintain its order. So if I were to traverse through the linked list from the root to its trail with this insertion -->
Insertion: 1 2 3
It should output -->
Output: 1 2 3
So far I have this code below. All this code does is output my insertion in reverse. So it prints ->
3
2
1
I want the program to maintain its insertion order by modifying my addLast() method. So when I print my Linked List it comes out the same way I inserted it.
public class LinkedListMeth
{
public static void main(String[] args)
{
FirstLinkedList list = new FirstLinkedList();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.traverseLast();
}
}
class FirstLinkedList
{
private class Node
{
private Node next;
private int data;
}
private Node last = null;
public void addLast(int d)
{
Node newNode = new Node();
newNode.data = d;
newNode.next = last;
last = newNode;
}
public void traverseLast()
{
Node head = last;
while (head != null)
{
System.out.println(head.data);
head = head.next;
}
}
If you want to stick with your exact current design, then one option to print the list in start-to-finish order would be to use recursion, something like this: