Add an element at first and last position of linked list

Following methods are used to add an element at first and last position of linked list:

  • addFirst(): Inserts the specified element at the beginning of the list.
  • offerFirst(): Inserts the specified element at the front of the list.
  • addLast(): Appends the specified element to the end of the list.
  • offerLast(): Inserts the specified element at the end of the list.
  • offer(): Adds the specified element as the tail (last element) of the list.

Example:

package com.w3spoint;
 
import java.util.LinkedList;
 
public class Test {
  public static void main(String args[]){
	LinkedList<String> linkedList = new LinkedList<String>();
	linkedList.add("Jai");
	linkedList.add("Mahesh");
	linkedList.add("Naren");
	linkedList.add("Vivek");
	linkedList.add("Vishal");
	linkedList.add("Hemant");
	System.out.println("Actual LinkedList:"+linkedList);
	System.out.println("Adding element at first position");
	linkedList.addFirst("Ajay");
        System.out.println(linkedList);
        System.out.println("Adding element at first position");
        linkedList.offerFirst("Nidhi");
        System.out.println(linkedList);
	System.out.println("Adding element at last position");
	linkedList.addLast("Vikas");
        System.out.println(linkedList);
        System.out.println("Adding element at last position");
        linkedList.offerLast("Binod");
        System.out.println(linkedList);
        System.out.println("Adding element at last position");
        linkedList.offer("Sachin");
        System.out.println(linkedList);
  }
}

Output

Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
Adding element at first position
[Ajay, Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
Adding element at first position
[Nidhi, Ajay, Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
Adding element at last position
[Nidhi, Ajay, Jai, Mahesh, Naren, Vivek, Vishal, Hemant, Vikas]
Adding element at last position
[Nidhi, Ajay, Jai, Mahesh, Naren, Vivek, Vishal, Hemant, Vikas, Binod]
Adding element at last position
[Nidhi, Ajay, Jai, Mahesh, Naren, Vivek, Vishal, Hemant, Vikas, Binod, Sachin]
Please follow and like us:
Content Protection by DMCA.com