说说LinkedList在作为队列使用时的常用方法
时间: 2024-05-23 16:10:55 浏览: 18
当LinkedList被用作队列时,它通常会使用以下常用方法:
1. add(element):向队列的末尾添加一个元素,并返回true,如果该操作失败,则引发一个IllegalStateException异常。
2. offer(element):向队列的末尾添加一个元素,并返回true,如果该操作失败,则返回false。
3. remove():从队列的头部删除一个元素,并将其返回。如果队列为空,则引发NoSuchElementException异常。
4. poll():从队列的头部删除一个元素,并将其返回。如果队列为空,则返回null。
5. element():返回队列的头部元素,但不会将其删除。如果队列为空,则引发NoSuchElementException异常。
6. peek():返回队列的头部元素,但不会将其删除。如果队列为空,则返回null。
相关问题
编写程序使用LinkedList构造“队列”(queue)数据结构并测试
好的,以下是Java语言的示例代码:
```java
import java.util.LinkedList;
public class Queue {
private LinkedList<Object> list = new LinkedList<Object>();
public void enqueue(Object item) {
list.addLast(item);
}
public Object dequeue() {
return list.removeFirst();
}
public boolean isEmpty() {
return list.isEmpty();
}
public int size() {
return list.size();
}
}
```
以上代码定义了一个名为Queue的类,其中使用了Java标准库中的LinkedList作为队列的底层数据结构。enqueue方法将元素添加到队列的末尾,dequeue方法从队列的开头取出并移除元素,isEmpty方法用于判断队列是否为空,size方法返回队列中元素的个数。
以下是一个简单的测试程序:
```java
public class TestQueue {
public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue("a");
queue.enqueue("b");
queue.enqueue("c");
System.out.println("队列大小:" + queue.size());
System.out.println("出队元素:" + queue.dequeue());
System.out.println("出队元素:" + queue.dequeue());
System.out.println("队列大小:" + queue.size());
queue.enqueue("d");
System.out.println("出队元素:" + queue.dequeue());
System.out.println("队列是否为空:" + queue.isEmpty());
}
}
```
运行测试程序,输出如下:
```
队列大小:3
出队元素:a
出队元素:b
队列大小:1
出队元素:c
队列是否为空:false
```
可以看到,程序成功地使用LinkedList构造了一个队列,并通过测试验证了其功能。
LinkedList实现队列
LinkedList实现队列的思路是利用链表的头尾指针,将元素添加到队尾,取出元素从队头开始取,实现先进先出的队列数据结构。
Java代码如下:
```
public class LinkedListQueue<E> {
private LinkedList<E> linkedList;
public LinkedListQueue() {
linkedList = new LinkedList<>();
}
public void enqueue(E e) {
linkedList.addLast(e);
}
public E dequeue() {
return linkedList.removeFirst();
}
public int size() {
return linkedList.size();
}
public boolean isEmpty() {
return linkedList.isEmpty();
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)