Java如何反转LinkedList元素的顺序?
为了反转LinkedList元素的顺序,我们可以使用class的reverse(List<?>list)静态方法java.util.Collections。这是示例:
package org.nhooo.example.util; import java.util.LinkedList; import java.util.Collections; public class LinkedListReverseOrder { 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("Output in original order:"); System.out.println("========================="); for (String grade : grades) { System.out.println("Grade = " + grade); } //颠倒链表对象中的元素顺序。 Collections.reverse(grades); System.out.println("Output in reverse order:"); System.out.println("========================="); for (String grade : grades) { System.out.println("Grade = " + grade); } } }
这是程序的输出:
Output in original order: ========================= Grade = A Grade = B Grade = C Grade = D Grade = E Grade = F Output in reverse order: ========================= Grade = F Grade = E Grade = D Grade = C Grade = B Grade = A