请问这段代码的算法有何问题?
    private void copy( LinkedList otherList )
    {
     LinkedListNode newNode;
     LinkedListNode current;        first=new LinkedListNode();    
     first=null;
     last=new LinkedListNode();
    
    
     if( otherList.first==null )
     {
     first=null;
     last=null;
     count=0;
    
     }
    
     else
     {
     boolean second=true;
     count=otherList.count;
     current=otherList.first;
     first.data=current.getData();
     first.nextNode=null;            last=first;
    
     current=current.getNextNode();
    
         while( current!=null )
         {
     newNode=new LinkedListNode();
         newNode.data=current.getData();
         newNode.nextNode=null;
         
         if( second )
             first.nextNode=last;
    
         last.nextNode=newNode;
         last=newNode;         current=current.getNextNode();
         second=false;
    
     }//end while
    
     }//end else
    
    }//end void copy 
请问这段代码的算法有何问题?是用来复制一个链表

解决方案 »

  1.   

    private LinkedList copy(LinkedList otherList) {        LinkedList resultList = null;        if (otherList == null) {
                return resultList;
            }        resultList = otherList.clone(); 
            
            return resultList;
        }
      

  2.   

    这只是浅拷贝,显而易见的是楼主要实现的深层拷贝.
    简单看了一下代码,罗列一些简单问题:
    1.为什么new之后要赋值为null
    first=new LinkedListNode();    
    first=null;
    2.
    if( otherList.first==null )
    改为
    if( otherList.getFirst()==null )
    3.
    count=otherList.count;
    改为
    count=otherList.size();
    4.
    current=otherList.first;
    改为
    current=(LinkedListNode)otherList.getFirst();
    5.
    current=(LinkedListNode)otherList.getFirst();
    first.data=current.getData();
    first.nextNode=null;
    last=first;//为什么把输入链表的first赋值给last,想反转链表么??
    6.
    while( current!=null )
    {
    newNode=new LinkedListNode();
    newNode.data=current.getData();
    newNode.nextNode=null;//为什么把链表的指向下一节点指针置空???
    7.
    last.nextNode=newNode;
    last=newNode;//这样写就表示一个节点指向自己,也就是这个节点的下一个节点是自己
    ..................