LinkedList源码分析
1.有双链表组成,哪两个?first,last。
添加last链表
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++;
}
new Node<>(l, e, null);这个是重点
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
在这里看来链表中存储着这个数的前一个数,和后一个数
add(E e)
public boolean add(E e) {
linkLast(e);
return true;
}
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++;
}
在last链表添加
push(E e)
public void push(E e) {
addFirst(e);
}
表头添加
输出
Iterator iterator=linkedList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
!!!尽量不要在foreach方法中使用remove,add方法
remove()
public E remove() {
return removeFirst();
}
删除头链表
demo
LinkedList linkedList=new LinkedList();
linkedList.add("1");
linkedList.add("2");
linkedList.add(3);
//先进先出
System.out.println(linkedList.getFirst()+" "+linkedList.getLast());
Iterator iterator=linkedList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
linkedList=new LinkedList();
linkedList.push("1");
linkedList.push(2);
linkedList.push(3);
//先进后出,像栈
Iterator iterator1=linkedList.iterator();
while (iterator1.hasNext()){
System.out.println(iterator1.next());
}
输出:1 3
1
2
3
3
2
1
还没有评论,来说两句吧...