Java Program to Add Element at First and Last Position of a Linked list

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to add element at first and last position of a linked list. The java.util.LinkedList class operations perform we can expect for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

Below is a demonstration of the same −

Suppose our input is

Input list: [Java, Scalaa, C++]

The desired output would be

The list after adding elements is: [JVA, Java, Scalaa, C++, Spark]

Algorithm

Step 1 - START
Step 2 - Declare a LinkedList namely input_list.
Step 3 - Define the values.
Step 4 - Use the in-built function addFirst() and addLast() to add elements to the first and last positions respectively.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.*;
public class Demo {
   public static void main(String args[]){
      LinkedList<String> input_list = new LinkedList<String>();
      input_list.add("Java");
      input_list.add("Scalaa");
      input_list.add("C++");
      System.out.println("The list is defined as: " + input_list);
      input_list.addFirst("JVA");
      input_list.addLast("Spark");
      System.out.println("The list after adding elements is: " + input_list);
   }
}

Output

The list is defined as: [Java, Scalaa, C++]
The list after adding elements is: [JVA, Java, Scalaa, C++, Spark]

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

import java.util.*;
public class Demo {
   static void add_elements(LinkedList<String> input_list){
      input_list.addFirst("JVA");
      input_list.addLast("Spark");
      System.out.println("The list after adding elements is: " + input_list);
   }
   public static void main(String args[]){
      LinkedList<String> input_list = new LinkedList<String>();
      input_list.add("Java");
      input_list.add("Scalaa");
      input_list.add("C++");
      System.out.println("The list is defined as: " + input_list);
      add_elements(input_list);
   }
}

Output

The list is defined as: [Java, Scalaa, C++]
The list after adding elements is: [JVA, Java, Scalaa, C++, Spark]
raja
Updated on 29-Mar-2022 12:41:13

Advertisements