package Text;public class ListTest<T> {
Node<T> node;
public ListTest(){
node=new Node<T>();
node.next=null;
node.head=null;
node.tail=null;
}

public void add(T t){
if(node.tail==null&&node.head==null){
node.obj = t;
node.head=node;
node.tail=node;
}else{//说明链表里有数据;
node.next=new Node<T>();
node=node.next;
node.obj=t;
node.tail=node;
}
}

public void printNode(){
System.out.println(node.tail.obj);
while(node.next!=null){
System.out.println(node.obj);
node=node.next;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
ListTest<String> ls=new ListTest<String>();
ls.add("aaa");
System.out.println("add b");
ls.add("bbb");
System.out.println("add b");
ls.add("ccc");
ls.printNode();
}
}class Node<T>{
T obj;
Node<T> next;
Node<T> head;
Node<T> tail;
public Node(){
next=null;
head=null;
tail=null;
}
}
这是代码,老是出问题,请求个位大虾帮忙啊!在此谢过……

解决方案 »

  1.   

    可以运行啊
    add b
    add b
    ccc请问LZ想问什么
      

  2.   

    首先你到底想实现什么样的链表没有说,链表也分好几种,
    我修改了你的代码,做了个简单点的链表,你参考下。另外你问问题的时候再你的代码中最好加点注释。public class ListTest<T> {
    Node<T> root;//表头 public ListTest() {
    root = new Node<T>();
    root.next = null;
    root.head = null;
    root.tail = null;
    root.obj  = null;
    } public void add(T t) {
    if (root.obj==null) {
    root.obj = t;
    root.head = root;
    root.tail = root;
    } else {// 说明链表里有数据;
    Node newNode = new Node<T>();
    newNode.obj = t;
    Node lastNode = getNext(root);
    lastNode.next = newNode;
    root.tail = newNode;
    }
    } public Node getNext(Node node){//目的获取链表中从头节点到最后一个节点(最后节点的next为null)
    if(node.next!=null){
    return getNext(node.next);
    }else{
    return node;
    }
    }
    public void printNode() {
    /*System.out.println(node.tail.obj);
    while (node.next != null) {
    System.out.println(node.obj);
    node = node.next;

    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }*/
    print(root);
    }

    public void print(Node node){
    System.out.println(node.obj);
    if(node.next!=null){
    print(node.next);
    }
    } public static void main(String[] args) {
    ListTest<String> ls = new ListTest<String>();
    ls.add("aaa");
    ls.add("bbb");
    ls.add("ccc");
    ls.add("eee");
    ls.printNode();
    }
    }class Node<T> {
    T obj;
    Node<T> next;
    Node<T> head;
    Node<T> tail; public Node() {
    next = null;
    head = null;
    tail = null;
    }
    }