LinkedList
1.概念
LinkedList: 实现一个链表。由这个类定义的链表也可以像栈或队列一样被使用。
定义类:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
2.构造方法
无参构造:为空
public LinkedList() {
}
有参构造:将一个集合构造为LinkedList
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
3. linkFirst方法
头插法:
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
4.linkLast方法
尾插法:
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
5.getFirst、getLast 方法
getFirst:得到第一个值
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
getLast :得到最后一个值
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
6. removeFirst、removeLast方法
移除一个值:
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
移除最后一个值:
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
7. contains方法
查找某一个值是否存在:
public boolean contains(Object o) {
return indexOf(o) != -1;
}
8.addAll方法
将一个集合全部添加:
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
将一个集合添加至index位置:
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
9.peek、element方法
peek:获取第一个结点的值,如果为空,输出null
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
element:获取第一个结点的值,如果为空,抛异常
public E element() {
return getFirst();
}
10.push、pop
push:相同于头插法
public void push(E e) {
addFirst(e);
}
pop:删除第一个结点
public E pop() {
return removeFirst();
}