Sunday, June 4, 2023

How to add element at the head and tail of a LinkedList in Java? Example

To add elements at the head and tail of a LinkedList in Java, you can use the addFirst() and addLast() methods provided by the LinkedList class. 

Here's an example:



import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        // Creating a LinkedList
        LinkedList linkedList = new LinkedList<>();

        // Adding elements at the head using addFirst()
        linkedList.addFirst("Element 1");
        linkedList.addFirst("Element 2");
        linkedList.addFirst("Element 3");

        System.out.println("LinkedList after adding at the head: " + linkedList);

        // Adding elements at the tail using addLast()
        linkedList.addLast("Element 4");
        linkedList.addLast("Element 5");
        linkedList.addLast("Element 6");

        System.out.println("LinkedList after adding at the tail: " + linkedList);
    }
}

In this example, we create a LinkedList called linkedList. We use the addFirst() method to add elements at the head of the list. We add three elements: "Element 1", "Element 2", and "Element 3". Then, we use the addLast() method to add elements at the tail of the list. We add three more elements: "Element 4", "Element 5", and "Element 6". Finally, we print the updated LinkedList. The output of this example will be:


LinkedList after adding at the head: [Element 3, Element 2, Element 1]
LinkedList after adding at the tail: [Element 3, Element 2, Element 1, Element 4, Element 5, Element 6]


As you can see, the elements are added at the head and tail of the LinkedList as expected.

No comments:

Post a Comment