日期:2014-05-20  浏览次数:20635 次

一个关于linkList的问题,请教高手解答疑惑
先看代码,如下:
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();
    }
}  

我的疑问在53行中说了,怎么都没弄明白,我明明没有对head进行赋值,最后的结果却是打印head的时候,可以将所有插入的值都打印出来
------解决方案--------------------
for ( p = head; p != null; p = p.next)
   这里p=head,这是把head的对象引用赋值给p,就也就是对象head的地址值给了p,p发生改变,head值也会变了