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