自定义一个简单的链表

随笔
自定义Linkedlist一个链表

public class setLinkedList<E> {
	  	private jiedian diyi;
	  	private jiedian zuihou;
	  	
	  	private int size;
	  
	  	public void add(int indx,E element) {
	  		
	  		
	  		chackrange(indx); 
	  		
			jiedian newjiedian = new jiedian(element);
			jiedian laojie = getjiedian(indx);
			
			if(laojie!=null) {
			jiedian shang = laojie.shang;
			
			shang.xia = newjiedian;
			newjiedian.shang  = shang;
			
			newjiedian.xia = laojie;
			laojie.shang = newjiedian;
			}
			
		}
	  	

	  	public void remove(int indx) {
	  		chackrange(indx);
	  		
			jiedian jie = getjiedian(indx);
			
			if(jie!=null) {
				jiedian up = jie.shang ;
				jiedian down = jie.xia ; 
				
				if(up!=null) {
				up.xia =down;
				}
				if(down!=null) { 
				down.shang  = up;
				}
				if(indx==0) {
					diyi=down ;
				}
				if(indx==size-1) {
					zuihou = up;
				}
				size--;
			}
		}
	  	
	  	
	  	
	  	public E get(int indx) {
	  		
	  		jiedian jie = getjiedian(indx);
	  		chackrange(indx);
	  		
	  		return jie!=null?(E)jie.element :null ;
	  	}
	  	private void chackrange(int indx) {
	  		
	  		if(indx<=0||indx>size-1) {
	  			throw new RuntimeException("索引数字不合法"+indx);
	  		}
	  	}
	  	
	  	
	  	private jiedian getjiedian(int indx) {
	  		
	  		chackrange(indx);
	  		
	  		
	  		jiedian jie = null;

	  		
	  		if(indx<=(size>>1)) {
	  			jie =  diyi;
	  			
	  			for(int i=0;i<indx;i++) {
	  		
		  			jie=jie.xia ;
		  		}
	  		}else {
	  			jie = zuihou;
	  			for(int i=size-1;i>indx;i-- ) {
	  				jie = jie.shang;
	  			}
	  		}
	  		return jie;
		}
	  	
	  	
	  	public void add(E element) {
			jiedian jie = new jiedian(element);
			
			if(diyi==null) {
				//jie.shang=null;
				//jie.xia=null;
				diyi = jie;
				zuihou = jie;
			}else {
				jie.shang=zuihou;
				jie.xia =null;
				zuihou.xia  = jie;
				zuihou = jie;
				
			}
			size++;
		}
		@Override
		public String toString() {
			//[a,b,c] diyi = a   zuihou =c
			StringBuilder sb = new StringBuilder("[");
			jiedian ji = diyi;
			while (ji!=null) {
				sb.append(ji.element+"," );
				ji = ji.xia;
			}
			sb.setCharAt(sb.length()-1, ']'); 
			return sb.toString();
		}
	  	public static void main(String[] args) {
			setLinkedList<String> li = new setLinkedList<>();
			li.add("a");
			li.add("b");
			li.add("c");
			li.add("d");
			li.add("e");
			li.add("f");
			li.add("g");
			System.out.println(li);
			li.add(6, "xyz");
			System.out.println(li);
			
		}
	  	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值