Given a Linked List in Java, the task is to insert elements at first and last position in this LinkedList.
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]
This can be achieved with the help of LinkedList.addFirst() and LinkedList.addLast() methods of LinkedList class in Java.
Below is the implementation of the above approach:
Linked list: [e, e, k] Updated Linked list: [G, e, e, k, s]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.