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.
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.
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.
Please Login to comment...