Tuesday 13 March 2012

Remove first and last elements of LinkedList Java example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.LinkedList;
 
public class RemoveFirstLastElementsLinkedListExample {
 
  public static void main(String[] args) {
   
    //create LinkedList object
    LinkedList lList = new LinkedList();
   
    //add elements to LinkedList
    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");
   
    System.out.println("LinkedList contains : " + lList);
   
     Object object = lList.removeFirst();
     System.out.println(object + " has been removed from the first index
                                                           of LinkedList");
     System.out.println("LinkedList now contains : " + lList);
       
      object = lList.removeLast();
      System.out.println(object + " has been removed from the last index
                                                           of LinkedList");
      System.out.println("LinkedList now contains : " + lList);
 
  }
}
 
/*
Output would be
 
LinkedList contains : [1, 2, 3, 4, 5]
1 has been removed from the first index of LinkedList
LinkedList now contains : [2, 3, 4, 5]
5 has been removed from the last index of LinkedList
LinkedList now contains : [2, 3, 4]
*/

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...