CodesJava

Easy learning with example program codes

how to add an element at first and last position of linked list?


LinkedList:

The LinkedList class extends AbstractSequentialList and implements the List and Deque interface. It uses linked list data structure to store elements. It can contain duplicate elements. It is not synchronized.

Note: It not provides the random access facility.

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.codesjava;
 
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]


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap