操作
- 获取链表中的元素个数
- 返回链表是否为空
- 在链表的index位置添加元素
- 在链表头添加元素
- 在链表末尾添加元素
- 获取链表第index位置元素
- 获取链表第一个元素
- 获取链表最后一个元素
- 修改链表第index位置元素
- 查找链表中是否含有元素e
- 删除index位置的元素
- 删除第一个元素
- 删除最后一个元素
- 删除元素e
时间复杂度分析
添加操作:O(n)
addLast(e) O(n)
addFirst(e) O(1)
add(index, e) O(n/2) = O(n)
删除操作:O(n)
removeLast(e) O(n)
removeFirst(e) O(1)
remove(index, e) O(n/2) = O(n)
修改操作:
set(index, e) O(n)
查找操作:O(n)
get(index) O(n)
contains(e) O(n)
如果只对链表的头部进行增和删操作,时间复杂度是O(1).
如果只查找链表头的元素,时间复杂度是O(1)
源码实现
public class LinkedList<E> {
private class Node{
public E e;
public Node next;
public Node(E e, Node next){
this.e = e;
this.next = next;
}
public Node(E e){
this(e, null);
}
public Node(){
this(null, null);
}
@Override
public String toString(){
return e.toString();
}
}
private Node dummyHead;
private int size;
public LinkedList(){
dummyHead = new Node();
size = 0;
}
// 获取链表中的元素个数
public