Java Program to Add elements to a LinkedList



In this article, we will understand how to add elements to 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

Run the program

The desired output would be

The elements added to the lists are: [Java, Python, Scala, Shell]

Algorithm

Step 1 - START
Step 2 - Declare a linkedlist namely input_list
Step 3 – Using the nuilt-in function add(), we add the elements to the list
Step 4 - Display the result
Step 5 - Stop

Example 1

Here, we add elements at the end of the list.

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args){
      LinkedList<String> input_list = new LinkedList<>();
      System.out.println("A list is declared");
      input_list.add("Java");
      input_list.add("Python");
      input_list.add("Scala");
      input_list.add("Shell");
      System.out.println("The elements added to the lists are: " + input_list);
   }
}

Output

A list is declared
The elements added to the lists are: [Java, Python, Scala, Shell]

Example 2

Here, we add elements at specified position of the list.

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args){
      LinkedList<String> input_list = new LinkedList<>();
      input_list.add("Java");
      input_list.add("Python");
      input_list.add("JavaScript");
      System.out.println("The list is defined as: " + input_list);
      input_list.add(1, "Scala");
      System.out.println("The list after adding element at position 1: " + input_list);
   }
}

Output

The list is defined as: [Java, Python, JavaScript]
The list after adding element at position 1: [Java, Scala, Python, JavaScript]

Advertisements