双向链表

JAVA实现双向链表终极解析!!熟练使用接口

注意:

get、set、add、remove、entry、clear

注意entry的循环:

       for (Entry e = header.previous; e != header; e = e.previous) {}  

新节点的创建: 

Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);  

此时新加节点已知道其前后节点,但其前节点并不知道后节点发生变化,后节点也不知道前节点发生变化,所以分别将新节点赋给他们。

双向链表节点:

private static class Entry<E> {    
        E element;    
        Entry<E> next;    
        Entry<E> previous;    
        
        Entry(E element, Entry<E> next, Entry<E> previous) {    
            this.element = element;    
            this.next = next;    
            this.previous = previous;    
        }    
    }

实现:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable{
        
	private transient Entry<E> header = new Entry<E>(null, null, null);    
      
	public LinkedList() {    
		header.next = header.previous = header;    
	} 
    
	public E get(int index) {
		return entry(index).element;
	}
	
	public E set(int index, E element) {
		Entry<E> e = entry(index);
		E oldVal = e.element;
		e.element = element;
		return oldVal;
	}
	
	//  根据给定的索引值离表头近还是离表尾近决定从头还是从尾开始遍历    
	private Entry<E> entry(int index) {      
		if (index < 0 || index >= size)      
		    throw new IndexOutOfBoundsException("Index: "+index+      
							", Size: "+size);      
		Entry<E> e = header;      
		if (index < (size >> 1)) { //如果较靠近有表头      
		    for (int i = 0; i <= index; i++)      
			e = e.next;      
		} else { //较靠近表尾      
		    for (int i = size; i > index; i--)      
			e = e.previous;      
		}      
		return e;      
	}   
	
	
	//默认的添加动作,可以看到这个方法是把新元素添加 到表尾    
	public boolean add(E e) {      
		addBefore(e, header); //加到头结点之前 ,即表尾      
		return true;      
	}
	
	private Entry<E> addBefore(E e, Entry<E> entry) {      
		 Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);      
		 newEntry.previous.next = newEntry; //将新结点与前后结点相连接       
		 newEntry.next.previous = newEntry;      
		 size++;      
		 modCount++;      
		 return newEntry;      
	}
	
	 //默认的删除动作是删除链表的第一个元素,所以说在默认情况下,LinkedList其实扮*演的是一个队列的角色    
	public E remove() {      
		 return removeFirst();      
	}
	
	public E removeFirst() {
		return remove(header.next);
	}
	
	private E remove(Entry<E> e) {
		if (e == header)
			throw new NoSuchElementException();

		E result = e.element;
		e.previous.next = e.next;
		e.next.previous = e.previous;
		e.next = e.previous = null;
		e.element = null;
		size--;
		modCount++;
		return result;
	}
	
	
	public void clear() {
		Entry<E> e = header.next;
		while (e != header) {
			Entry<E> next = e.next;
			e.next = e.previous = null;
			e.element = null;
			e = next;
		}
		header.next = header.previous = header;
		size = 0;
		modCount++;
	}
}

相关推荐