日期:2014-05-20 浏览次数:20759 次
public class LinkedArray {
private Entry root;
private int count;
public static void main(String[] args) {
LinkedArray la = new LinkedArray();
for (int i = 0; i < 10; i++) {
la.add(i+"");
}
}
public LinkedArray() {
}
private class Entry{
private String data;
private Entry next;
private boolean add(String data){//有死循环
while(this.next!=null){
this.next.add(data);
}
if(this.next==null){
this.next = new Entry(data);
}
return true;
}
public Entry(String data) {
this.data = data;
}
}
public boolean add(String value){
if(value == null){
return false;
}
this.count++;
if(root==null){
root = new Entry(value);
}else{
this.root.add(value);
}
return true;
}
}
import java.util.Iterator;
/**
* 带表头的单向链表。
* 可以用迭代器,遍历里面的元素。
*/
public class OneWayList<T> implements Iterable<T>{
class Entry{
T data;
Entry next;
public Entry(T data) {
this.data = data;this.next=null;
}
}
/**
* 单向链表的表头,表头不存放数据。
*/
private Entry header = new Entry(null);
public void add(T data){
Entry tail = header;
while(tail.next!=null){
tail = tail.next;//指针后移
}
tail.next = new Entry(data);
}
/**
* 迭代器
*/
private class Iter implements Iterator<T>{
Entry p = header;
public boolean hasNext() {
return p.next!=null;
}
public T next() {
p = p.next;
return p.data;
}
public void remove() {
throw new IllegalStateException("Not support this operation.");
}
}
public Iterator<T> iterator() {
return new Iter();
}
/**
* 测试用例
*/
public static void main(String[] args) {
OneWayList<String> la = new OneWayList<String>();
for (int i = 0; i < 10; i++) {
la.add(i+"");
}
for(String s :la){
System.out.println(s);
}
}
}
public class LinkedArray {