Java LinkedList 中獲取第一個和最後一個元素


使用 java.util.LinkedList.getFirst() 和 java.util.LinkedList.getLast() 方法可以分別獲取 LinkedList 的第一個和最後一個元素。這兩種方法均不需要任何引數。

演示該方法的程式如下

示例

 現場演示

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList l = new LinkedList();
      l.add("John");
      l.add("Sara");
      l.add("Susan");
      l.add("Betty");
      l.add("Nathan");
      System.out.println("The first element of the Linked List is : " + l.getFirst());
      System.out.println("The last element of the Linked List is : " + l.getLast());
   }
}

上述程式的輸出如下

The first element of the Linked List is : John
The last element of the Linked List is : Nathan

現在,讓我們來了解上述程式。

建立了 LinkedList l。然後,使用 LinkedList.getFirst() 和 LinkedList.getLast() 分別獲取連結串列的第一個和最後一個元素。演示該程式碼片段如下

LinkedList l = new LinkedList();
l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");
System.out.println("The first element of the Linked List is : " + l.getFirst());
System.out.println("The last element of the Linked List is : " + l.getLast());

更新於:2019 年 7 月 30 日

528 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.