您的位置:首页 > 编程语言 > Java开发

Java实现泛型链表

2007-05-02 23:10 369 查看
import java.util.Iterator;

public class LinkList<V> implements Iterable<V> {

Data<V> first;
Data<V> last;
Data<V> current;
int count;

public LinkList() {

}

public boolean add(V obj)
{
boolean ret = false;
Data<V> data = new Data<V>(obj);
if(first == null)
{
first = data;
last = data;
current = data;
ret = true;
}
else
{
last.next = data;
data.previous = last;
last = data;
last.next = null;
ret = true;
}
count++;
return ret;
}

public V get(int index)
{
return getData(index).data;
}

public V getFirst()
{
return first.data;
}

public V getLast()
{
return last.data;
}

public int indexOfx(V obj)
{
int index = -1;
current = first;
while(count-- > 0)
{
if(current.data.equals(obj))
{
++index;
break;
}
current = current.next;
}
return index;
}

public boolean removeAt(int index)
{
boolean ret = false;
if(checkIndex(index))return ret;
if(index == 0)
{
first = first.next;
first.previous = null;
ret = true;
}
else if(index == count - 1)
{
last = last.previous;
last.next = null;
ret = true;
}
else
{
Data<V> _f,_l;
current = getData(index);
System.out.println(current.data);
_f = current.previous;
_l = current.next;
_f.next = _l;
_l.previous = _f;
ret = true;
}

count--;

return ret;
}

public V remove(V obj)
{
current = first;
int i = -1;
while(i < count)
{
i++;
if(current.data.equals(obj))break;
current = current.next;
}
removeAt(i);
return current.data;
}

public boolean insert(int index , V obj)
{
boolean ret = false;
Data<V> data = new Data<V>(obj);
if(index == 0)
{
current = first;
first = data;
first.next = current;
first.previous = null;
}
else if(index == count -1)
{
current = last;
last = data;
last.previous = current;
last.next = null;
}
else
{
Data<V> _u,_l;
current = getData(index);
_u = current.previous;
_l = current;
_u.next = data;
data.previous = _u;
_l.previous = data;
data.next = _l;
}
count++;
return ret;
}

public Data<V> getData(int index)
{
if(checkIndex(index))throw new ArrayIndexOutOfBoundsException("数组越界!");
current = first;
while(index-- > 0)
current = current.next;
return current;
}

public boolean checkIndex(int i)
{
boolean ret = false;
if(i < 0 || i > count - 1)ret = true;
return ret;
}

class Data<T>
{
T data;
Data<T> previous;
Data<T> next;
Data(T t)
{
this.data = t;
}
}

// 实现Iterable 接口可使用 for-each 类型循环厉遍。
@SuppressWarnings("unchecked")
public Iterator iterator() {
return new Itr();
}

class Itr implements Iterator
{
int cursor = 0;
int lastRet = -1;

public boolean hasNext() {
boolean ret = false;
if(cursor != count)ret = true;
return ret;
}

public Object next() {
return getData(cursor++).data;
}

public void remove() {
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: