Add element at the beginning and end of the LinkedList

In the previous post, we have seen how to add element at a specified index.In this post, we will see how to add element at the beginning and end of the LinkedList.

There are methods addFirst() and addLast() which will be used to add the element at the beginning and end of the LinkedList.

Syntax:

public void addFirst(Element e) : Element ‘e’ will be added at the beginning of the LinkedList.

public void addLast(E e): Element ‘e’ will be added at the end of the LinkedList.

Example:

import java.util.LinkedList;

public class LinkedListEx {

	public static void main(String[] args) {
		LinkedList<String> fruits1 = new LinkedList<String>();
		fruits1.add("Orange");
		fruits1.add("Mango");
		fruits1.add("Apple");
		fruits1.add("Grapes");
		
		fruits1.addFirst("Date");  // Date will be added at the beginning of the list
		System.out.println("Element 'Date' will be added :"+ fruits1);
		
		fruits1.addLast("Banana"); // Banana will be added at the end of the list
		System.out.println("Element 'Banana' will be added :"+ fruits1);
	}
}

Output:

Element ‘Date’ will be added :[Date, Orange, Mango, Apple, Grapes]
Element ‘Banana’ will be added :[Date, Orange, Mango, Apple, Grapes, Banana]


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...