Java实现单链表终极版

  • Post author:
  • Post category:java


public class LinkedList2<E> implements List {
	private int size;
	private Node<E> first;
	private static int ELEMENT_NOT_FOUND=-1;
	private static class Node<E>{
		Object element;
		Node<E> next;
		public Node(E element, Node<E> next) {
			super();
			this.element = element;
			this.next = next;
		}		
	}

	@Override
	public void clear() {
		size=0;
		first=null;
	}

	@Override
	public int size() {
		return size;
	}
	public int indexOf(E element){
		if(element==null){
			for(int i=0;i<size;i++){
				if(node(i).element==null){
					return i;
				}
			}
		}else{
			for(int i=0;i<size;i++){
				if(node(i).element.equals(element)){
					return i;
				}
			}
		}
		return ELEMENT_NOT_FOUND;
	}
	
	@Override
	public String toString() {
		StringBuilder sb=new StringBuilder();
		Node<E> node=first;
		sb.append("[");
		for(int i=0;i<size;i++){
			sb.append(node(i).element);
			if(i!=size-1){
				sb.append(",");
			}
		}
		sb.append("]");
		return sb.toString();
	}

	@Override
	public boolean isEmpty() {
		return size==0;
	}

	@Override
	public boolean contains(Object element) {
		for(int i=0;i<size;i++){
			if(element==null){
				if(node(i).element==null){
					return true;
				}
			}else{
				if(node(i).element.equals(element)){
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void add(Object element) {
		add(size,element);
	}

	@Override
	public Object get(int index) {
		return node(index).element;
	}

	@Override
	public Object set(int index, Object element) {
		Node<E> temp=node(index);
		E e=(E) temp.element;
		temp.element=element;
		return e;
	}

	@Override
	public void add(int index, Object element) {
		rangeCheckForAdd(index);
		
		if(index==0){
			first=new Node(element,first);
		}else{
			Node<E> prev=node(index-1);
			Node<E> temp=new Node(element,prev.next);
			prev.next=temp;
		}
		
		size++;
	}

	@Override
	public E remove(int index) {
		Node<E> temp=null;
		if(index==0){
			temp=first;
			first=first.next;
		}else{
			Node<E> prev=node(index-1);
			temp=prev.next;
			prev.next=prev.next.next;
		}
		size--;
		return (E) temp.element;
	}
	private Node node(int index){
		rangeCheck(index);
		Node temp=first;
		for(int i=0;i<index;i++){
			temp=temp.next;
		}
		return temp;
	}
	private void outBounds(int index){
		throw new IndexOutOfBoundsException("Index:"+index+",Size: "+size);
	}
	private void rangeCheck(int index){
		if(index<0||index>=size){
			outBounds(index);
		}
	}
	private void rangeCheckForAdd(int index){
		if(index<0||index>size){
			outBounds(index);
		}
	}

}



版权声明:本文为zb199566原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。