How to add element at the specific position of the LinkedList?

How to add element at the specific position of the LinkedList?

Previous Home Next

 

This program will shows how to add the element at the specific position of the index.

 we  add element at specific position of index using add(int index,element) method
 public void add(int index,
                E element) Inserts the specified element at the specified position in this list

Call the add(int index,element) method to add the element at the specific position of the index 

 


package Example;
import java .util.LinkedList;
import java .util.Iterator;
public class LinklistExample {
/**
* @param args
*/
public static void main(String[] args) {
LinkedList Lst= new LinkedList(); // create object of LinkedList

// add elements to the LinkedList using add method
Lst.add("4");
Lst.add("6");
Lst.add("8");
Lst.add("10");
Lst.add("12");
Lst.add("14");
Lst.add("16");
Lst.add("18");

System.out.println("The elements of LinkedList prior to addition of other elemnts are:"+Lst);
Lst.addLast("20"); // add element at the last of linklist
System.out.println("Now the LinkedList contains:"+Lst);
Lst.add(5, "11");
System.out.println(" after inserting specific element at specific position :" +Lst);

The elements of LinkedList prior to addition of other elemnts are:[4, 6, 8, 10, 12, 14, 16, 18]
after adding element Now the LinkedList contains:[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
 after inserting specific element at specific position :[2, 4, 6, 8, 10, 11, 12, 14, 16, 18, 20]
Previous Home Next