- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete first and last element from a LinkedList in Java
The first element can be deleted from a LinkedList by using the method java.util.LinkedList.removeFirst(). This method does not have any parameters and it returns the first element of the LinkedList.
The last element can be deleted from a LinkedList by using the method java.util.LinkedList.removeLast(). This method does not have any parameters and it returns the last element of the LinkedList.
A program that demonstrates this is given as follows −
Example
import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("Apple"); l.add("Mango"); l.add("Pear"); l.add("Orange"); l.add("Guava"); System.out.println("The LinkedList is: " + l); l.removeFirst(); l.removeLast(); System.out.println("The LinkedList is: " + l); } }
Output
The LinkedList is: [Apple, Mango, Pear, Orange, Guava] The LinkedList is: [Mango, Pear, Orange]
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>(); l.add("Apple"); l.add("Mango"); l.add("Pear"); l.add("Orange"); l.add("Guava"); System.out.println("The LinkedList is: " + l);
The methods LinkedList.removeFirst() and LinkedList.removeLast() is used to remove the elements at the beginning and end of the Linked List respectively. Then the LinkedList is again displayed. A code snippet which demonstrates this is as follows −
l.removeFirst(); l.removeLast(); System.out.println("The LinkedList is: " + l);
- Related Articles
- Get first and last elements from Java LinkedList
- Retrieve the last element from a LinkedList in Java
- Remove a specific element from a LinkedList in Java
- How to delete last element from a map in C++
- How to delete last element from a set in C++
- First element and last element in a JavaScript array?
- How to delete last element from a List in C++ STL
- Get first and last elements from Vector in Java
- Golang program to get the first and last element from a slice
- Search a particular element in a LinkedList in Java
- Replace an element of a Java LinkedList
- How to get first and last elements from ArrayList in Java?
- Add a single element to a LinkedList in Java
- How to remove an element from ArrayList or, LinkedList in Java?
- Delete the first 10 characters from JTextArea in Java
