62,614
社区成员
发帖
与我相关
我的任务
分享
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;
}
}