# 一、简介

LinkedList底层是双向链表结构,链表将元素存放在单独的节点中[非连续的地址空间],通过nextpre将节点连接起来,因此插入和删除元素的时间复杂度为O(1),也不存在容量问题和扩容方法。LinckedList同时实现了List接口和Deque接口,我们既可以将它看作容器,也可以看作队列,还可以作为Java官方已经建议不要使用Stack类。关于栈和队列,首选ArrayQeque,它有比LinkedList更好的性能。LinckedList是非线程安全的,主要是为了效率,所以没有实现Synchronize同步,如果需要多线程并发操作,可以采用Collections.synchronizedList()方法进行包装。LinkedList允许存放Null和重复元素。

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    // 长度
    transient int size = 0;

    // 指向上一个节点
    transient Node<E> first;

    //指向下一个节点
    transient Node<E> last;
1
2
3
4
5
6
7
8
9
10
11
12
LinkedList

# 二、使用

【1】集合方法

方法 说明
boolean add(E e) 尾插e
void add(int index, E element) e插入到index位置
boolean addAll(Collection<? extends E> c) 尾插c中的元素
E remove(int index) 删除index位置元素
boolean remove(Object o) 删除遇到的第一个o
E get(int index) 获取下标 index 位置元素
E set(int index, E element) 将下标index位置元素设置为element
void clear() 清空
boolean contains(Object o) 判断o是否在线性表中
int indexOf(Object o) 返回第一个o所在下标
int lastIndexOf(Object o) 返回最后一个o的下标
List<E> subList(int fromIndex, int toIndex) 截取部分list

【2】栈方法

方法 等效方法
push(e) addFirst(e)
pop() removeFirst()
peek() peekFirst()

peekFirstgetFirst的区别:他们都获得了指向LinkedList中第一个元素的指针,而不对其进行任何更改。如果列表为空peekFirst返回null,而getFirst抛出NoSuchElementException如果列表为空。

【3】队列方法

方法 等效方法
add(e) addLast(e)
offer(e) offerLast(e)
remove() removeFirst()
poll() pollFirst()
element() getFirst()
peek() peekFirst()

offeradd的区别:offer属于offer in interface Dequeadd属于add in interface Collection。当队列为空时候,使用add方法会报错,而offer方法会返回false

#

(adsbygoogle = window.adsbygoogle || []).push({});