w3resource

Java: Insert the specified element at the front of a linked list


7. Insert at Front

Write a Java program to insert the specified element at the front of a linked list.

Sample Solution:-

Java Code:

import java.util.LinkedList;
  public class Exercise7 {
  public static void main(String[] args) {
   // create an empty linked list
     LinkedList<String> l_list = new LinkedList<String>();
   // use add() method to add values in the linked list
          l_list.add("Red");
          l_list.add("Green");
          l_list.add("Black");
     System.out.println("Original linked list:" + l_list);    
  // Add an element to front of LinkedList
     l_list.offerFirst("Pink");
     System.out.println("Final linked list:" + l_list);  
 }	
}

Sample Output:

Original linked list:[Red, Green, Black]                               
Final linked list:[Pink, Red, Green, Black]

Pictorial Presentation:

Java Collection Linked-list: Insert the specified element at the front of a linked list.

Flowchart:

Flowchart: Insert the specified element at the front of a linked list.

For more Practice: Solve these Related Problems:

  • Write a Java program to insert an element at the front of a linked list and then shift existing elements accordingly.
  • Write a Java program to insert an element at the front using a dummy head node and then remove the dummy afterward.
  • Write a Java program to implement a method that prepends an element and returns the new head of the linked list.
  • Write a Java program to use recursion to add an element at the beginning of a linked list and then print the list.

Go to:


PREV : Insert at First and Last.
NEXT : Insert at End.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.