How to add element at the first position of the LinkedListHow to add element at the first position of the LinkedList
Previous | Home | Next |
This program hows how to add the element at the first position of the LinkedList.
To add element at the Linked List addfirst() method is used here.
public void addFirst(E e) method is used to add element at the first position of the LinkedList .it will Inserts the specified element at the beginning of this list
After adding elements to the LinkedList call the addfirst() along with object of LinkedList .pass the value to the method which you want to add as parameter.
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.addFirst("2"); // add element at the first positionof linklist
System.out.println("After adding element at the first position linkedList is:"+Lst);
The elements of LinkedList prior to addition of other elemnts are:[4, 6, 8, 10, 12, 14, 16, 18]
After adding element at the first position linkedList is:[2, 4, 6, 8, 10, 12, 14, 16, 18]
Previous | Home | Next |