Sunday 11 May 2014

LinkedList : addFirst : Insert Element at the beginning of Linked List

public void addFirst(E e)
Inserts the specified element at the beginning of this list.

import java.util.*;

class LinkedListAddFirst{
 public static void main(String args[]){
  LinkedList<Integer> myList = new LinkedList<Integer> ();
  
  System.out.println("Add 10 to the myList");
  myList.addFirst(10);
  System.out.println("Elements in myList are\n" + myList);
  
  System.out.println("\nAdd 20 to the myList");
  myList.addFirst(20);
  System.out.println("Elements in myList are\n" + myList);
  
  System.out.println("\nAdd 30 to the myList");
  myList.addFirst(30);
  System.out.println("Elements in myList are\n" + myList);
  
  System.out.println("\nAdd 40 to the myList");
  myList.addFirst(40);
  System.out.println("Elements in myList are\n" + myList);
 }
}

Output
Add 10 to the myList
Elements in myList are
[10]

Add 20 to the myList
Elements in myList are
[20, 10]

Add 30 to the myList
Elements in myList are
[30, 20, 10]

Add 40 to the myList
Elements in myList are
[40, 30, 20, 10]



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment