Java LinkedList remove first and last elements

Introduction

To remove first and last elements from LinkedList in Java

linkedList.removeFirst(object);
linkedList.removeLast(object);

Full source


import java.util.Arrays;
import java.util.LinkedList; 
 
public class Main { 
  public static void main(String args[]) { 
    // Create an array list. 
    LinkedList<String> al = new LinkedList<String>(); 
     //from   w  w  w . j  a  va2  s  .c om
    // Add elements to the array list. 
    al.add("CSS"); 
    al.add("SQL"); 
    al.add("Java");
    al.add("CSS"); 
    al.add("Javascript"); 
    al.add("CSS"); 
    al.add("HTML");
    al.add("CSS"); 
    al.add("Demo2s.com"); 
    al.add(1, "Hi"); 
 
    System.out.println(al);
    
    // Remove elements from the linked list. 
    al.removeFirst(); 
    al.removeFirstOccurrence("CSS"); 
    al.removeLast(); 
    al.removeLastOccurrence("CSS"); 
 
    System.out.println("Contents after deletion: " 
                       + al); 
  } 
}



PreviousNext

Related