LinkedList 仿源码

 

 

 

 

 

package javacore;

/**
 * @author baoyou E-mail:[email protected]
 * @version 创建时间:2015年9月7日 下午12:31:13 des:
 */
public class LinkedList<E> {

	public static class Node<E> {
		public E obj;
		public Node<E> prev = null;
		public Node<E> next = null;

		Node(Node<E> prev, E element, Node<E> next) {
			this.obj = element;
			this.next = next;
			this.prev = prev;
		}
	}

	transient int size = 0;
	transient Node<E> first;
	transient Node<E> last;

	public 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++;
	}

	E unlink(Node<E> x) {
		final E element = x.obj;
		final Node<E> next = x.next;
		final Node<E> prev = x.prev;

		if (prev == null) {
			first = next;
		} else {
			prev.next = next;
			x.prev = null;
		}

		if (next == null) {
			last = prev;
		} else {
			next.prev = prev;
			x.next = null;
		}

		x.obj = null;
		size--;
		return element;
	}

	public boolean add(E e) {
		linkLast(e);
		return true;
	}

	public boolean remove(E e) {
		if (e == null) {
			for (Node<E> x = first; x != null; x = x.next) {
				if (x.obj == null) {
					unlink(x);
					return true;
				}
			}
		} else {
			for (Node<E> x = first; x != null; x = x.next) {
				if (e.equals(x.obj)) {
					unlink(x);
					return true;
				}
			}
		}
		return false;
	}

	public E getFirst() {
		return first.obj;
	}

	public E getLast() {
		return last.obj;
	}

	public static void main(String[] args) {
		LinkedList ll = new LinkedList<>();
		ll.add(1);
		ll.add(2);
		System.out.println(ll.getFirst() + " --- " + ll.getLast());
		ll.remove(2);
		System.out.println(ll.getFirst() + " --- " + ll.getLast()); 
	}

}

 

 

 



 

你可能感兴趣的:(java,源码,LinkedList)