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]
- Find the position of an element in a Java TreeMap
- Implementing a Linked List in Java using Class
- List add(int index, E element) method in Java
- CharBuffer position() methods in Java with Examples
- ByteBuffer position() methods in Java with Examples
- Buffer position() methods in Java with Examples
- Frequently asked questions for Java Developer Position from a fresher
- Creating a Cell at specific position in Excel file using Java
- Program to convert List of String to List of Integer in Java
- Program to convert List of Integer to List of String in Java
- Add the given digit to a number stored in a linked list using recursion
- How to iterate over a 2D list (list of lists) in Java
- How to add an element to an Array in Java?
- ArrayDeque element() Method in Java
- Remove first element from ArrayList in Java
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.