先看java之中linkedlist的源码
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
/**
* Constructs an empty list.
*/
public LinkedList() {
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* Links e as first element.
*/
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++;
}
/**
* Links e as last element.
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
首先我们需要复习一下对象的知识,对于一个对象而言,他的赋值只是简单的将该对象的引用进行了赋值,而不是该对象进行了复制。对于函数调用之中的参数,我们也是把对象的引用进行了复制,所以要注意。
从源码之中我们可以看到,linkedlist就是一个链表,他吧原来的对象包装成node之后放到list里面去,删除的时候就把这个node给清空然后调整list就可以了。
对于linkedlist的增删改查:
增加对于原本的对象不进行改变,只是在node的element成员赋值为了该对象的引用
删除:只是把node的element成员赋值为空,并没有改变对象的引用
修改:是对于对象的引用的修改,所以我们的修改会改变原有的东西,请注意
查:没有影响
接下来看一下linkedlist的一些函数
为了模拟queue
我们有
element()展示最前面的元素
peek()展示最前面的元素
offer()加一个元素在最后面
poll()删除最后的元素
remove()删除最后的元素
为了模拟stack
我们有
push()加在最前面的元素(加倍注意这里)
pop()删除最前面元素(加倍注意这里)
peek()展示最前面的元素
建议平常使用的时候就用
addFirst()
addLast()
removeFirst()
removeLast()
getFirst()
getLast()
最后介绍一下两个链表之间怎么复制
注意这里有个坑,直接复制的话,就是原本的list的引用,导致了原本的list改变,复制的list也会改变。
所以使用clone进行浅拷贝,这样的拷贝是没有复制原本list之中的对象的,也就是还是原本对象的引用,对象没有进行复制,代码如下。
必须要记得进行类型强转
LinkedList<Integer> list1=new LinkedList<Integer>();
LinkedList<Integer> list2=new LinkedList<Integer>();
list1.addFirst(1);
list2=(LinkedList<Integer>)list1.clone();
list1.removeFirst();
System.out.println(list1);
System.out.println(list2);
- 使用clone进行list复制
- clone浅拷贝
- clone后强转