算法-Java中常用的数据结构
1. 列表 List
1.1 ArrayList
List<Integer> list = new ArrayList<>();
| 方法名 | 说明 |
|---|---|
| size() | 获取列表的长度 |
| isEmpty() | 列表为空返回true,否则返回false |
| add(int index,E element) | 添加元素,其中index是可选参数 |
| get(int index) | 通过索引获取元素 |
| set(int index, E element) | 替换指定索引的元素 |
| remove(int index) / remove(E element) | 删除指定索引的元素/指定元素 |
| toArray(T[] arr) | 将列表转化为数组,其中T [] arr 是可选参数,是用于存储的数组 |
菜鸟教程ArrayList链接:https://www.runoob.com/java/java-arraylist.html
2. 栈 Stack
Stack<Integer> st = new Stack<Integer>();
| 方法名 | 说明 |
|---|---|
| empty(): boolean | 判断栈是否为空 |
| peek(): Object | 返回栈顶元素,但不弹出 |
| push(Object element): Object | 压栈 |
| pop(): Object | 弹出栈顶元素 |
菜鸟教程Stack链接:https://www.runoob.com/java/java-stack-class.html
3. 队列
Queue,Deque是两个接口。
LinkedList同时实现了这两个接口,可以用于实例化单向/双向队列。
图1 |
图2 |
3.1 单向队列 Queue
Queue<Integer> queue = new LinkedList<Integer>();
| 方法名 | 说明 |
|---|---|
| isEmpty(): boolean | isEmpty()是父接口Collection的方法 |
| add(Object element): boolean | 入队,超出最大容量时add()会抛出异常 |
| offer(Object element): boolean | 入队,超出最大容量时offer()会返回false |
| remove(): Object | 出队,队列为空时remove()会抛出异常 |
| poll(): Object | 出队,队列为空时poll()会返回null |
| element(): Object | 获取队头元素,队列为空时element()会抛出异常 |
| peek(): Object | 获取队头元素,队列为空时peek()返回null |
3.2 双向队列 Deque
Deque<Integer> deque = new LinkedList<Integer>();
| 方法名 | 说明 |
|---|---|
| addFirst() | - |
| addLast() | - |
| offerFirst() | - |
| offerLast() | - |
| removeFirst() | - |
| removeLast() | - |
| pollFirst() | - |
| pollLast() | - |
| peekFirst() | - |
| peekLast() | - |
菜鸟教程LinkedList链接:https://www.runoob.com/manual/jdk11api/java.base/java/util/LinkedList.html
图1
图2