Java Examples - Adding Element to Linked List


Advertisements


Problem Description

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

Solution

Following example shows how to add an element at the first and last position of a linked list by using addFirst() and addLast() method of Linked List class.

import java.util.LinkedList;

public class Main {
   public static void main(String[] args) {
      LinkedList<String> lList = new LinkedList<String>();
      lList.add("1");
      lList.add("2");
      lList.add("3");
      lList.add("4");
      lList.add("5");
      System.out.println(lList);
      
      lList.addFirst("0");
      System.out.println(lList);
      
      lList.addLast("6");
      System.out.println(lList);
   }
}

Result

The above code sample will produce the following result.

1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6

The following is an another sample example to add an element at first and last position of a linked list?

import java.util.LinkedList;

public class Demo {
   public static final void main(String[] args) {
      LinkedList lList = new LinkedList();
      System.out.println("Number of items in the list: " + lList.size());
      String item1 = "foo";
      String item2 = "bar";
      String item3 = "sai";
      String item4 = "prasad";
      
      lList.add(item1);
      lList.add(item2);
      lList.addFirst(item3);
      System.out.println(lList);
      lList.addLast(item4);
      System.out.println(lList);
      System.out.println("Number of items in the list: " + lList.size());
   } 
}

The above code sample will produce the following result.

Number of items in the list: 0
[sai, foo, bar]
[sai, foo, bar, prasad]
Number of items in the list: 4

java_data_structure.htm

Advertisements