Last active
March 28, 2016 15:11
-
-
Save anonymous/65dcc77d2a1e459d6c7e to your computer and use it in GitHub Desktop.
What's wrong there ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Iterator; | |
/** | |
* | |
*/ | |
public class DoubleLinked<Item> implements Iterable<Item>{ | |
private Node head; | |
private Node tail; | |
private int N; | |
public DoubleLinked(){ | |
head = new Node(); | |
tail = new Node(); | |
} | |
private class Node{ | |
Item item; | |
Node left; | |
Node right; | |
} | |
public int size(){ | |
return N; | |
} | |
public boolean isEmpty(){ | |
return size()==0; | |
} | |
public void push(Item item){ | |
if(isEmpty()){ | |
Node newFirst = new Node(); | |
newFirst.item=item; | |
head.right = newFirst; | |
tail.left=newFirst; | |
}else { | |
Node oldFirst = head.right; | |
Node newFirst = new Node(); | |
newFirst.item=item; | |
newFirst.right=oldFirst; | |
oldFirst.left=newFirst; | |
head.right=newFirst; | |
} | |
N++; | |
} | |
public Item remove(Node node){ | |
Item item = node.item; | |
if(node==head.right){ | |
head.right = node.right; | |
node=null; | |
}else if(node==tail.left){ | |
tail.left=node.left; | |
node=null; | |
}else { | |
Node last = node.left; | |
Node next = node.right; | |
last.right = next; | |
next.left=last; | |
node=null; | |
} | |
N--; | |
return item; | |
} | |
@Override | |
public ListIterator iterator() { | |
return new ListIterator(); | |
} | |
private class ListIterator implements Iterator<Item>{ | |
Node current = head.right; | |
@Override | |
public boolean hasNext() { | |
if(current!=null && size()>0){ | |
return true; | |
}else { | |
return false; | |
} | |
} | |
@Override | |
public Item next() { | |
Item item = current.item; | |
//System.out.println("current:地址"+current); | |
current=current.right; | |
return item; | |
} | |
@Override | |
public void remove() { | |
} | |
} | |
public static void main(String[]args){ | |
DoubleLinked d = new DoubleLinked<Integer>(); | |
for(int i=0;i<5;i++) d.push(i); | |
System.out.println(d.remove(d.tail.left)); | |
// System.out.println(d.remove(d.tail.left)); | |
int k = 0; | |
for(Iterator i = d.iterator();i.hasNext();) { | |
System.out.println("next:"+i.next()); | |
k++; | |
} | |
System.out.println("size:"+d.size()); | |
//System.out.println(d.tail.left.item); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment