javadata-structureslinked-list

Linked List addLast() method is not working as expected


As per the definition addLast(), the addLast() method is used to add element to the last of the list. But here in the following code that's not happening.

LinkedList<Integer> demo = new LinkedList<>();
demo.addLast(15);
demo.addFirst(1);
demo.add(10);
System.out.println(demo);

The output is

[1, 15, 10]

But as per the definition the output should have been

[1, 10, 15]

Because the addLast() method should be adding 15 to the last of the list. I'm not sure what exactly is the issue here.

Code snippet : Code snippet


Solution

  • addLast adds an item at the end of the list - it doesn't mean it will remain at the end of list when additional items are added.

    Let's track the code: