要从链表中删除第一个或最后一个元素,我们可以使用LinkedList类提供的removeFirst()和removeLast()方法。
package org.nhooo.example.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); } } }
该程序打印出以下结果:
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