How do I remove the first and last item from LinkedList?
To remove the first or the last elements from the linked list we can use the removeFirst() and removeLast() methods provided by the LinkedList class. package org.kodejava.util; import java.util.LinkedList; public class LinkedListRemoveItems { public static void main(String[] args) { LinkedList<String> grades = new LinkedList<>(); grades.add("A"); grades.add("B"); grades.add("C"); grades.add("D"); grades.add("E"); grades.add("F"); System.out.println("Original values are:"); Sy...
Article by Wayan · Source: Kode Java ↗
To remove the first or the last elements from the linked list we can use the removeFirst() and removeLast() methods provided by the LinkedList class.
package org.kodejava.util;
import java.util.LinkedList;
public class LinkedListRemoveItems {
public static void main(String[] args) {
LinkedList<String> grades = new LinkedList<>();
grades.add("A");
grades.add("B");
grades.add("C");
grades.add("D");
grades.add("E");
grades.add("F");
System.out.println("Original values are:");
System.out.println("====================");
for (String grade : grades) {
System.out.println("Grade: " + grade);
}
grades.removeFirst();
grades.removeLast();
System.out.println("New values are:");
System.out.println("====================");
for (String grade : grades) {
System.out.println("Grade: " + grade);
}
}
}
This program print out the following result:
Original values are:
====================
Grade: A
Grade: B
Grade: C
Grade: D
Grade: E
Grade: F
New values are:
====================
Grade: B
Grade: C
Grade: D
Grade: E
Comments 0
Share your questions, experiences, or feedback about this article.
Sign in with Google to leave a comment.
Sign in with Google
No comments yet. Be the first to share your feedback.