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());
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP