2019年1月19日-Linkedlist的实现

自定义实现linkedlist的底层代码:

package cn.liu.three;

public class MyLinkedList {
	Node first;
	Node last;
	private int size;
	
	public int size() {
		return size;
	}
	private Node node(int index) {
		rangecheck(index);
		Node temp=null;
		if(first!=null) {
			temp=first;
			for(int i=0;i<index;i++) 
			     {
			       temp=temp.next;
			     }
			           }
		return temp;
	}
	private void rangecheck(int index) {
		if(index<0||index>=size){
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	Node n=new Node();
	public void add(Object obj) {
		if(first==null) {
			n.setPrevious(null);
			n.setObj(obj);
			n.setNext(null);
			
			first=n;
			last=n;
		}else {
			//直接往last节点后增加新的节点
			n.setPrevious(last);
			n.setObj(obj);
			n.setNext(null);
			
			last.setNext(n);
			last=n;
		}
		size++;
	}
	
	public void remove(int index) {
		rangecheck(index);
		Node temp=node(index);
		if(temp!=null) {
						 Node up=temp.previous;
						 Node down=temp.next;
						 up.next=down;
						 down.next=up;
						}
			size--;
	}
	
	public Object get(int index) {
		rangecheck(index);
		Node temp=node(index);
		if(temp!=null) {
			return temp.obj;
		}
			return null;
		}
	
	public void add(int index,Object obj) {
		rangecheck(index);
		Node temp=node(index);
		Node newnode=new Node();
		newnode.obj=obj;
		
		if(temp!=null) {
			Node up=temp.previous;
	
			up.next=newnode;
			newnode.previous=up;
			
			newnode.next=temp;
			temp.previous=newnode;
			size++;
		}
	}
	
	
	
	
	public static void main(String[] args) {
		MyLinkedList list=new MyLinkedList();
		list.add("wert");
		list.add("123");
		System.out.println(list.size());
		list.add("aaa");
		list.add("bbb");
//		list.add(1,"BBBB");
		list.add("ccc");
		list.add("ddd");
		list.add("eee");
//		list.remove(1);
		System.out.println(list.get(0)); 
		
		
	}
	
	

}
package cn.liu.three;

public class Node {
	 Node previous;
	 Object obj;
	 Node next;
	
	public Node() {
		
	}
	
	

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



	public Node getPrevious() {
		return previous;
	}



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



	public Object getObj() {
		return obj;
	}



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



	public Node getNext() {
		return next;
	}



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



	
	

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值