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
- ByteBuffer position() methods in Java with Examples
- Buffer position() methods in Java with Examples
- CharBuffer position() methods in Java with Examples
- Creating a Cell at specific position in Excel file using Java
- Frequently asked questions for Java Developer Position from a fresher
- Program to convert List of Integer to List of String in Java
- Program to convert List of String to List of Integer in Java
- Add the given digit to a number stored in a linked list using recursion
- How to add an element to an Array in Java?
- Queue element() method in Java
- ConcurrentLinkedDeque element() method in Java
- Deque element() method 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 firstname.lastname@example.org. 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.