LinkedList addFirst() Method in Java

Published by user on

The addFirst(E element) method of LinkedList appends the specified element at the beginning of this linked list. It does not return anything.

Syntax

void addFirst(E e)

Parameters

e is the element to be added to the linked-list

Return Value

It doesn't return anything

Program

import java.util.LinkedList;

public class LinkedListAddFirstExample {

        public static void main(String[] args) {

                LinkedList oddNumbers = new LinkedList();
                oddNumbers.add(5);
                oddNumbers.add(7);
                oddNumbers.add(9);
                oddNumbers.add(11);

                System.out.println("Linked List elements: " + oddNumbers);
                oddNumbers.addFirst(3);
                System.out.println("Linked List elements after adding 3 at first position: " + oddNumbers);
        }
}
Output
Linked List elements: [5, 7, 9, 11]
Linked List elements after adding 3 at first position: [3, 5, 7, 9, 11]
Categories: Java

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *