LinkedList.poll()
时间: 2024-04-21 21:16:22 浏览: 19
LinkedList.poll() 方法是 Java 中 LinkedList 类的一个方法,用于从列表的开头检索并删除第一个元素。如果列表为空,则返回 null。
该方法的语法如下:
```java
public E poll()
```
其中,E 是列表中的元素类型。
该方法执行以下操作:
1. 检查列表是否为空。如果是空的,则返回 null。
2. 获取列表的第一个元素。
3. 删除列表的第一个元素。
4. 返回被删除的元素。
示例:
```java
LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("C");
String firstElement = list.poll();
System.out.println(firstElement); // 输出:A
System.out.println(list); // 输出:[B, C]
```
poll() 方法常用于队列的实现,它可以将列表作为队列使用,实现先进先出(FIFO)的数据结构。
相关问题
java LinkedList poll
`LinkedList` 类是 Java 中的双向链表实现。`poll` 方法用于从链表的头部移除并返回元素,如果链表为空,则返回 `null`。
以下是使用 `poll` 方法的示例代码:
```java
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("Apple");
linkedList.add("Banana");
linkedList.add("Orange");
System.out.println("LinkedList: " + linkedList);
String element = linkedList.poll();
System.out.println("Removed Element: " + element);
System.out.println("LinkedList after poll: " + linkedList);
}
}
```
输出结果:
```
LinkedList: [Apple, Banana, Orange]
Removed Element: Apple
LinkedList after poll: [Banana, Orange]
```
在上面的示例中,我们创建了一个 `LinkedList` 并添加了三个元素。然后我们使用 `poll` 方法移除并返回链表的头部元素,并打印出移除的元素以及修改后的链表内容。
queue.poll()
在Java中,queue.poll()是一个常用的方法,它用于获取并移除队列头部的元素。如果队列为空,它会返回null。下面是一个使用queue.poll()方法的例子:
```java
Queue<String> queue = new LinkedList<>();
queue.add("apple");
queue.add("banana");
queue.add("orange");
System.out.println(queue.poll()); // 输出:apple
System.out.println(queue.poll()); // 输出:banana
System.out.println(queue.poll()); // 输出:orange
System.out.println(queue.poll()); // 输出:null
```
在上面的例子中,我们首先创建了一个LinkedList类型的队列,并向其中添加了三个元素。然后我们使用queue.poll()方法依次获取并移除队列头部的元素,直到队列为空。在最后一次调用queue.poll()方法时,由于队列已经为空,它返回null。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)