1

LinkedList源码分析(四)

 1 year ago
source link: https://blog.51cto.com/u_13794952/5745728
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
LinkedList源码分析(四)_堆栈

🍁 作者:知识浅谈,CSDN博客专家,阿里云签约博主,InfoQ签约博主,华为云云享专家

📌 擅长领域:全栈工程师、爬虫、ACM算法

💒 公众号:知识浅谈

LinkedList源码分析(四)总结

正菜来了⛳⛳⛳

🎈LinkedList源码分析

🍮E peekFirst()

含义: 从列表中找到最开始的一个元素,如果first为null的话,就返回null,否则就返回f对应的item。

public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}

🍮E peekLast()

含义:从列表中找到最后一个元素,如果last为null的话,就返回null,否则就返回f对应的item。

public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}

🍮E pollFirst()

含义:检索并删除此列表的第一个元素,如果此列表为空,则返回 null。

public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}

🍮E pollLast()

含义:检索并删除此列表的最后一个元素,如果此列表为空,则返回 null。

public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}

🍮void push(E e)

含义:将元素推送到此列表表示的堆栈上。换句话说,在这个列表的前面插入元素。

public void push(E e) {
addFirst(e);
}

函数里边调用了addFirst(e),就是把e这个元素添加到list的第一个位置。

🍮E pop()

含义:这个的意思是从列表中删除第一个位置的元素,并返回删除的元素,函数里边嗲用的removeFirst就是这个含义。从此列表表示的堆栈中弹出一个元素。换句话说,删除并返回此列表的第一个元素。

public E pop() {
return removeFirst();
}

🍮E removeFirstOccurrence()

含义:删除此列表中第一次出现的指定元素(从头到尾遍历列表时)。如果列表不包含该元素,则它不变。

public boolean removeFirstOccurrence(Object o) {
return remove(o);
}

🍮boolean removeLastOccurrence(Object o)

含义:删除此列表中指定元素的最后一次出现(从头到尾遍历列表时)。如果列表不包含该元素,则它不变。

public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}

🍮ListIterator listIterator(int index)

含义:返回从指定index索引位置开始的一个迭代器,首先先判断index这个位置是不是超出链表的范围。

public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}

从上述函数中,我们可以看到,checkPositionIndex(index)是用来检查index是否满足要求的,接着我们往下看。

🍮void checkPositionIndex(int index)

含义:这个函数的意思就是检查index这个索引是否满足条件,index是否在链表的长度范围内,isPositionIndex()函数比较的index是否大于等于0且小于等于size,如果不在范围内,就抛出异常。

private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

以上是关于LinkedList源码中存在的部分函数的解读,希望有所帮助。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK