`

实现LindedList

 
阅读更多
public class MyLinkedList {
	public LinkedNode first;
	public LinkedNode last;
	public int size;

	public void add(Object obj) {
		LinkedNode n = new LinkedNode();
		if (first == null) {
			n.setPrevious(null);
			n.setObj(obj);
			n.setNext(null);

			first = n;
			last = n;
		} else {
			n.setPrevious(last);
			n.setObj(obj);
			n.setNext(null);
			last.setNext(n);
			last = n;
		}
		size++;
	}
	public int size() {
		return size;
	}
	private void rangeCheck(int index) {
		if (index >= size)
			throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
	}
	private String outOfBoundsMsg(int index) {
		return "Index: " + index + ", Size: " + size;
	}
	public Object get(int i) {
		// 考虑越界
		LinkedNode node = getNode(i);
		if(node!=null){
			return node.getObj();
		}
		return null;
	}
	public LinkedNode getNode(int i){
		rangeCheck(i);
		LinkedNode temp = null;
		if (first != null) {
			temp = first;
			for (int j = 0; j < i; j++) {
				temp = temp.getNext();
			}
		}
		return temp;
	}
	
	public void delete(int i) {
		if(null!=getNode(i)){
			LinkedNode temp = getNode(i);
			LinkedNode pre = temp.getPrevious();
			LinkedNode next = temp.getNext();
			pre.setNext(next);
			next.setPrevious(pre);
			size--;
		}
	}
	public void add(int i,Object obj) {
		LinkedNode n = new LinkedNode();
		if(first==null && i==0 && size==0){
			n.setPrevious(null);
			n.setObj(obj);
			n.setNext(null);
			first = n;
			last = n;
		} else{
			if(null!=getNode(i)){
				LinkedNode temp = getNode(i);
				LinkedNode pre = temp.getPrevious();
				LinkedNode next = temp.getNext();
				n.setObj(obj);
				if(pre==null){
					first = temp;
					n.setPrevious(first);
					first.setNext(n);
				}
				n.setPrevious(pre);
				pre.setNext(n);
				if(next==null){//如果找不到最后一个就是最后一个
					last = temp;
					n.setNext(last);
					last.setPrevious(n);
				}else{
					n.setNext(next);
					next.setPrevious(n);
				}
				
			}
		}
		size++;
	}
	public static void main(String[] args) {

		MyLinkedList list = new MyLinkedList();
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		list.delete(1);
		
		list.add(1, "ddd");
		System.out.println(list.get(1));
	}
}

 

public class LinkedNode {
	private LinkedNode previous;
	private Object obj;
	private LinkedNode next;
	public LinkedNode getPrevious() {
		return previous;
	}
	public void setPrevious(LinkedNode previous) {
		this.previous = previous;
	}
	public Object getObj() {
		return obj;
	}
	public void setObj(Object obj) {
		this.obj = obj;
	}
	public LinkedNode getNext() {
		return next;
	}
	public void setNext(LinkedNode next) {
		this.next = next;
	}
	 
}

 

0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics