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 and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Find first and last element of ArrayList in java
- List add(int index, E element) method in Java
- Get first and last elements from ArrayList in Java
- Swap the first and last character of a string in Java
- Add the given digit to a number stored in a linked list using recursion
- Find the position of an element in a Java TreeMap
- Removing last element from ArrayList in Java
- Find the last element of a Stream in Java
- AbstractList add(int index, E element) method in Java with Examples
- How to add an element to an Array in Java?
- List add(E ele) method in Java with Examples
- List add() Method in Java with Examples
- Remove first element from ArrayList in Java
- Find the first element of a Stream in Java
- Java.util.ArrayList.add() Method in Java
- Frequently asked questions for Java Developer Position from a fresher
- Creating a Cell at specific position in Excel file using Java
- ByteBuffer position() methods in Java with Examples
- Buffer position() methods in Java with Examples
- CharBuffer position() methods in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.