java数据结构 四(双向链表)

package com;




/** 双向链表
 * 插入删除快,读取慢,
 * 让每个元素知道下个元素位置(内存地址)
 */
public class LinearTable {
	Entry table;
	public LinearTable(){
		table =new Entry();
	}
	
	
	class Entry{
		Object date;
		Entry next;
		Entry prior;
	}
	
	public void add(Object obj){
			Entry p=null,s=null;
			p=table;
			while(p!=null&&p.next!=null){
				s=p.next;
				p=s;
			}
			s=new Entry();
			s.date=obj;
			s.next=p.next;
			s.prior=p;
			p.next=s;
	}
	
	public void add(Object obj,int index){
		Entry p=null,s=null;
		p=table;
		int i=0;
		while(p!=null&&p.next!=null&&i<index){
			i++;
			p=p.next;
		}
		if((i+1)<index)
			 throw new IndexOutOfBoundsException("Index: "+i+", Size: "+index); 
		s=new Entry();
		s.date=obj;
		s.next=p.next;
		s.prior=p;
		p.next=s;
}
	public boolean del(int index){
		Entry p=null,s=null;
		p=table;
		int i=0;
		while(p!=null&&p.next != null&&(i<index+1)){
			s=p;
			p=p.next;
			i++;
		}
		if((i+1)<index)
			 throw new IndexOutOfBoundsException("Index: "+i+", Size: "+index); 
		if(p!=null){
			s.next=p.next;
			s.next.prior=s;
			p=null;
			return true;
		}
		return false;
}
	
	public boolean del(Object obj){
		Entry p=null,s=null;
		p=table;
		while(p!=null&&((p.date == null)||(!p.date.equals(obj)))){
			s=p;
			p=p.next;
		}
		if(p!=null){
			s.next=p.next;
			s.next.prior=s;
			p=null;
			return true;
		}
		return false;
}
	
	public boolean isElement(Object obj){
		Entry p=null;
		p=table;
		while(p!=null&&((p.date == null)||(!p.date.equals(obj)))){
			p=p.next;
		}
		return p!=null;
	}
	
	public static void main(String[] args) {
		LinearTable t=	new LinearTable();
		t.add("1");
		t.add("2");
		t.add("3");
//		t.add("11", 11);
		forech(t);
		boolean de=t.del(1);
		forech(t);

//		System.out.println(tableSizeFor(1));
	}
	
	
	public static void forech(LinearTable t){
		Entry e=t.table;
		while(e.next!=null){
			e=e.next;
			System.out.println(e.date);
		}
		System.out.println("------------");
	}
	
    static final int MAXIMUM_CAPACITY = 1 << 30;
    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
    
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值