Maintaining order of linked list insertion

778 Views Asked by At

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;
       }
   }
2

There are 2 best solutions below

2
On

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:

public void printFirstLinkedList(Node node) {
    if (node == null) return;

    printFirstLinkedList(node.next);

    System.out.print(node.data + " ");

    return;
}

printFirstLinkedList(yourList.last);
0
On

You should keep root of your linked list for traversing in insert order.

Here is an edited version of your code:

class FirstLinkedList {
    private class Node {
        private Node next;
        private int data;
    }

    private Node root = null;
    private Node last = null;

    public void addLast(int d) {
        Node node = new Node();
        node.data = d;
        if (root == null) {
            root = node;
            root.next = last;
            last = root;
        } else {
            last.next = node;
            last = last.next;
        }
    }

    public void traverseLast() {
        Node head = root;
        while (head != null) {
            System.out.println(head.data);
            head = head.next;
        }
    }
}

Output is :

1
2
3