容器第四课,JDK源代码分析,自己实现LinkedList,双向链表的概念_节点定义

package com.pkushutong.Collection;

public class Test03 {
	private Test03_01 first;	//第一个节点
	private Test03_01 last;		//最后一个节点
	
	private int size;
	
	public void add(Object obj){
		Test03_01 t = new Test03_01();
		if(first == null){
			t.setPrevious(null);
			t.setObj(obj);
			t.setNext(null);
			first = t;
			last = t;
		}else{
			//直接往last借点后增加新的节点
			t.setPrevious(last);
			t.setObj(obj);
			t.setNext(null);
			last.setNext(t);
			last = t;
		}
		size++;
	}
	
	public int size(){
		return size;
	}
	
	public Object get(int index){
		Test03_01 temp = node(index);
		return temp.obj;
	}
	
	public void remove(int index){
		Test03_01 temp = node(index);
		
		if(temp != null){
			Test03_01 up = temp.previous;
			Test03_01 down = temp.next;
			up.next = down;
			down.previous = up;
			size--;
		}
	}

	public void add(int index,Object obj){
		Test03_01 temp = node(index);
		Test03_01 newTest03_01 = new Test03_01();
		newTest03_01.obj = obj;
		if(temp != null){
			Test03_01 up = temp.previous;
			up.next = newTest03_01;
			newTest03_01.previous = up;
			
			newTest03_01.next = temp;
			temp.previous = newTest03_01;
			size++;
		}
	}
	
	private Test03_01 node(int index) {
		Test03_01 temp = null;
		if(first != null){
			temp = first;
			for(int i=0; i<index; i++){
				temp = temp.next;
			}
		}
		return temp;
	}
	
	public static void main(String[] args) {
		Test03 list = new Test03();
		list.add("123");
		list.add("234");
		list.add("345");
		//list.remove(1);
		list.add(1, "aaaa");
		System.out.println(list.get(1));
	}
}


package com.pkushutong.Collection;


/**
 * 用来表示一个节点
 * @author dell
 *
 */
class Test03_01{
	Test03_01 previous;
	Object obj;
	Test03_01 next;
	
	public Test03_01() {

	}

	public Test03_01(Test03_01 previous, Object obj, Test03_01 next) {
		super();
		this.previous = previous;
		this.obj = obj;
		this.next = next;
	}

	public Test03_01 getPrevious() {
		return previous;
	}

	public void setPrevious(Test03_01 previous) {
		this.previous = previous;
	}

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}

	public Test03_01 getNext() {
		return next;
	}

	public void setNext(Test03_01 next) {
		this.next = next;
	}
	
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值