java双向链表操作
有add(v) add(i.v) remove(i) get(i)
public class TowWayLinkList <T> implements Iterable<T>{
private class Node<U>{
private U item;
private Node<U> pre;
private Node<U> next;
public Node(Node<U> pre,U item, Node<U> next){
this.item = item;
this.pre = pre;
this.next = next;
}
}
private Node<T> first;
private Node<T> last;
private int N;
public TowWayLinkList(){
N=0;
}
public void add(T v){
Node<T> l = last;
Node<T> newNode = new Node<>(l, v, null);
last = newNode;
if(l == null){
first = newNode;
}else{
l.next = newNode;
}
N++;
}
public void add(int i,T v){
if(i <0|| i >N){
throw new RuntimeException("索引超限");
}
if(i == N){
add(v);
}else{
Node<T> current = getNode(i);
Node<T> pre = current.pre;
Node<T> nowData = new Node<>(pre, v, current);
if(pre == null){
first = nowData;
}else{
current.pre = nowData;
pre.next = nowData;
}
}
N++;
}
public T get(int i){
return getNode(i).item;
}
private Node<T> getNode(int i){
if(i < 0||i >= N){
throw new RuntimeException("索引超限");
}
if(i < (N >> 1)){
Node<T> x = first;
for (int j = 0; j < i; j++) {
x = x.next;
}
return x;
}else{
Node<T> x = last;
for (int j = N-1; j > i; j--) {
x = x.pre;
}
return x;
}
}
public void remove(int i){
if(i < 0||i> N){
throw new RuntimeException("索引超限");
}
if(i == N-1){
Node<T> a = last;
Node<T> pre = a.pre;
pre.next = null;
last = pre;
}else if(i == 0){
Node<T> a = first;
Node<T> next = a.next;
next.pre = null;
first = next;
}else{
Node<T> a = getNode(i);
Node<T> pre = a.pre;
Node<T> next = a.next;
pre.next = next;
next.pre = pre;
}
N--;
}
public static void main(String[] args) {
LinkedList lis1 = new LinkedList();
lis1.add(0, "2");
lis1.get(0);
TowWayLinkList<String> list = new TowWayLinkList<>();
list.add("111");
list.add("2222");
list.add("222232");
list.add("2222q111");
list.add("212121");
System.out.println("-------------");
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
@Override
public Iterator<T> iterator() {
return new LIterator();
}
private class LIterator implements Iterator<T>{
private Node<T> next;
private Node<T> lastReturned;
private int nextInt;
public LIterator(){
nextInt = 0;
this.next = first;
}
@Override
public boolean hasNext() {
return nextInt < N;
}
@Override
public T next() {
lastReturned = next;
next = next.next;
nextInt++;
return (T) lastReturned.item;
}
}
}
迭代器可能优点问题,超了索引,下次优化下。
|