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;
}
}
java数据结构 四(双向链表)
最新推荐文章于 2024-10-18 14:41:23 发布