Java循环链表交换不适用于头部

时间:2019-03-21 07:29:51

标签: java nodes circular-list

我有一种方法可以交换循环链表的两个节点

  • 它使用2个对象作为参数。该代码适用于以下情况 这两个对象都是头部的元素

    public void exchange(E a, E b) {
     Node<E> head = tail.getNext();
     if(a == b)
         return;
    
     if(isEmpty() || size == 1) //no exchange if size is 1
         return;
    
     if(size == 2){   //if size is two, head will be tail and tail will be head
         rotate();
     }
    
     else{
    
        Node<E> currA = head, prevA = null;    //search for first node
             if(head.getElement() == a){
             Node<E> temp = head;
             while(!temp.getNext().equals(head)){
                 temp = temp.getNext();
             }
             prevA = temp;
    
         }else if(tail.getElement() == a){
            currA = tail;
            while(!currA.getNext().equals(tail)){
                prevA = currA.getNext();
            }
        }else{
            while(!currA.getElement().equals(a)){
                prevA = currA;
                currA = currA.getNext();
                if(currA.getNext() == head)
                    break;
            }
        }
    
        Node<E> currB = head, prevB = null; //Search for second node
                  if(currB.getElement() == b){
             Node<E> temp = head;
         while(!temp.getNext().equals(head)){
             temp = temp.getNext();
         }
         prevB = temp;
    
         }else if(tail.getElement() == b){
             currB = tail;
            while(!currB.getNext().equals(tail)){
                prevB = currB.getNext();
            }
         }else{
             while(!currB.getElement().equals(b)){
                 prevB = currB;
                 currB = currB.getNext();
                 if(currB.getNext() == head)
                     break;
         }
     }
     System.out.println(currA.getElement() +" currentA"); //I get output for this
     System.out.println(currB.getElement() +" currentB");
     System.out.println(prevA.getElement() +" previousA");// Gives null pointer exception when object a is head 
     System.out.println(prevB.getElement() +" previousB");// Gives null pointer exception when object b is head
     prevA.setNext(currB);
     prevB.setNext(currA);
     Node<E> temp = currA.getNext();
     currA.setNext(currB.getNext());
     currB.setNext(temp);
     }
    

    }

我的代码能够提供和使用currA(和currB)
但是
如果a与head相同,则它不是空指针,而不是在if语句中分配prevA。如果b是head的元素,则发生相同的情况,则prevB为null。(代码在此处停止)

0 个答案:

没有答案