日期:2014-05-20 浏览次数:20708 次
package 数组;
public class LinkedList<T> {
private static class Node<T> {
T data;
Node<T> next;
Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
Node(T data) {
this(data, null);
}
}
private Node<T> head, tail;
public LinkedList() {
head = tail = null;
}
/**
* judge the list is empty
*/
public boolean isEmpty() {
return head == null;
}
/**
* 输出链表的所有序列的值
*/
public void traverse() {
if (isEmpty()) {
System.out.println("null");
} else {
for (Node<T> p = head; p != null; p = p.next)
System.out.println(p.data);
}
}
/**
* 插入链表的值从链表的最后一个序列开始
*/
public void addFromTail(T item) {
Node<T> newNode = new Node<T>(item);
Node<T> p = null;
if (!isEmpty()){
for ( p = head; p != null; p = p.next){
if(p.next == null){
/*这里出现了一个情况,当走完p.next = newNode的时候,p的值居然已经跟 head同步了,完全不用走 head = p这样的代码
* */
p.next = newNode;
break;
}
}
}else{
p = newNode;
head = p;
}
}
public static void main(String args[]){
LinkedList<String> test = new LinkedList<String>();
test.addFromTail("yan");
test.addFromTail("li");
test.addFromTail("yu");
test.traverse();
}
}