How to Add Element at First and Last Position of LinkedList in Java?
LinkedList is a part of Collection framework present inside java.util package. This class is an implementation of LinkedList data structure which is a linear data structure where the elements are not stored in a contiguous manner and every element is a separate object with a data field and address field. Now here we are given a Linked List, the task is pretty simple that is to insert elements at the first and last position in this LinkedList which is carried out with help of methods present inside the LinkedList class that is addFirst() and addLast() method.
Illustration:
Input : LinkedList: ['e', 'e', 'k'], insert at first = 'G', insert at last = 's'
Output: LinkedList: ['G', 'e', 'e', 'k', 's']
Input : LinkedList: [2, 3, 4], insert at first = 1, insert at last = 5
Output: LinkedList: [1, 2, 3, 4, 5]
As we mentioned above it can be achieved when aided with the help of addFirst() and addLast() methods of the LinkedList class.
Example:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
LinkedList<String> linkedList
= new LinkedList<String>();
linkedList.add( "e" );
linkedList.add( "e" );
linkedList.add( "k" );
System.out.println( "Linked list: " + linkedList);
linkedList.addFirst( "G" );
linkedList.addLast( "s" );
System.out.println( "Updated Linked list: "
+ linkedList);
}
}
|
Output:
Linked list: [e, e, k]
Updated Linked list: [G, e, e, k, s]
Note: add() and addLast() provide same functionality. LinkedList implements two interfaces, Deque and Queue. It inherits add() from Deque and addLast() from Queue.
Last Updated :
15 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...