【Java】LinkedList 底层原理,自己实现LinkedList

package test;

/**
 * 节点的类定义
 * @author 袁盛桐
 * @version 1.0
 */
class Node{
	Node previous;
	Object obj;
	Node next;
	
}

/**
 * 自己实现一个linkedlist,学习原理和底层实现
 * @author 袁盛桐
 * @version 1.0
 */
public class MyLinkedList {
	private Node first;
	private Node last;
	private int size;
	
	public int size() {
		return size;
	}
	
	/**
     * 检查输入的index是否在范围内
     */
    public void rangeCheck(int index){
        if(index<0||index>=size){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
	
	/**
	 * 返回指定位置对象
	 */
	public Object get(int index) {
		rangeCheck(index);
		Node temp = null;
		if(first!=null) {
			if(index<(size >> 1)) {
				temp = first;
				for(int i=0;i<index;i++) {
					temp = temp.next;
				}
			}else {
				temp = last;
				for(int i=size-1;i>index;i--) {
					temp = temp.previous;
				}
			}
			
		}
		return temp.obj;
	}

	/**
	 * 在末尾增加对象
	 * @param obj
	 */
	public void add(Object obj) {
		Node n = new Node();
		if(first == null) {
			n.previous=null;
			n.obj=obj;
			n.next=null;
			
			first = n;
			last = n;
		}else {
			n.previous=last;
			n.obj=obj;
			n.next=null;
			
			last.next=n;
			last = n;
		}
		size++;
	}
	
	/**
	 * 在制定位置增加对象
	 */
	public void add(int index, Object obj) {
		Node temp = null;
		if(first!=null) {
			temp = first;
			for(int i=0;i<index;i++) {
				temp = temp.next;
			}
		}
		Node newNode = new Node();
		newNode.obj = obj;
		if(temp!=null) {
			newNode.previous=temp.previous;
			newNode.next=temp;
			temp.previous=newNode;
			newNode.previous.next=newNode;
			size++;
		}
		
	}
	
	/**
	 * 删除索引位置的对象
	 * @param index
	 */
	public void remove(int index) {
		Node temp = null;
		if(first!=null) {
			temp = first;
			for(int i=0;i<index;i++) {
				temp = temp.next;
			}
		}
		temp.previous.next=temp.next;
		temp.next.previous=temp.previous;
		size--;
	}
	
	public static void main(String[] args) {
		MyLinkedList test = new MyLinkedList();
		test.add("111");
		test.add("222");
		test.add(1,"hhh");
		test.add("333");
		//test.remove(1);
		for(int i=0;i<test.size();i++) {
			System.out.println(test.get(i));
		}
}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}

猜你喜欢

转载自blog.csdn.net/weixin_38516944/article/details/81303042