Monday 18 May 2015

How to insert element in LinkedList

we can insert element in Linkedlist at a given index.for this we use add(int index,element).

import java.util.LinkedList;

public class AddElement {
   
    public static void main(String[] args) {
       
        LinkedList<String> linkedList = new LinkedList<String>();
       
        linkedList.add("Mumbai");
        linkedList.add("Delhi");
        linkedList.add("Noida");
        linkedList.add("Gao");
        linkedList.add("Patna");
        //print linkedlist
        System.out.println(" Linklist is = "+linkedList);
       
        /*
         * Inserts the specified element at the specified position
           in this list. Shifts the element currently at that position
           (if any) and any subsequent elements to the right
         */
       
        linkedList.add(2, "bangalore");
       
        System.out.println("After Insert Element Linkedlist is = "+linkedList);
       
    }

}

Output:

 Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]

After Insert Element Linkedlist is = [Mumbai, Delhi, bangalore, Noida, Gao, Patna]
 

No comments:

Post a Comment