2016-08-28 7 views
1

링크 된 목록에서 "임의의"노드를 제거하려고합니다. 제 방법 "T remove()"를 참조하십시오. NullPointerException 오류가 발생하지 않고 노드를 제거 할 수 없습니다.링크 된 목록에서 지정되지 않은 항목 제거

처음에는 목록에 아무것도 없으면 NULL을 반환합니다. 노드가 존재하면 numberofNodes를 반복하고 임의의 노드를 찾아 해당 노드를 삭제하려고합니다. 나는 일시적으로 다음 노드의 데이터를 가리키는 노드를 만들고 이전 노드가 currentNode 다음에있는 노드를 마치 존재하지 않는 것처럼 가리 키도록합니다.

내 논리가 잘못 되었나요?

private class Node{ 

     private T entry; 
     private Node next; 

     private Node(T entryPortion) 
     { 
      this(entryPortion, null); 
     } 

     private Node(T entryPortion, Node nextNode) 
     { 
      entry = entryPortion; 
      next = nextNode; 
     } 

    } 

    private Node node1; 
    private Node lastNode; 
    private int numItems; 

    public LinkedBag() //Establishes an empty bag 
    { 
     node1 = null; 
     numItems = 0; 
    } 

    @Override 
    public int getCurrentSize() 
    { 
     // Gets Size of Bag 
     return numItems; 
    } 

    @Override 
    public boolean isFull() 
    { 
     //Checks to see if bag is full, however since it is linked list there is no specified max size. Although maximum memory can be reached 
     return true; 
    } 

    @Override 
    public boolean isEmpty() { 
     // Checks to see if bag is empty 
     return node1 == null; 
    } 

    @Override 
    public boolean add(T newItem) { 
     // Adds something to the bag 
     Node newNode = new Node(newItem); 
     newNode.next = node1; 

     node1 = newNode; 
     numItems++; 
     return true; 
    } 

    @Override 
    public T remove() { 
     // Removes random item from bag 

     if(node1.equals(null)) 
     { 
      return null; 
     } 

     else 
     { 
     int randItem = new Random().nextInt(numItems); 
     Node currentNode = node1; 
     Node previousNode = node1; 
     for (int i = 0; i < randItem; i++) 
      { 
      previousNode = currentNode; 
      currentNode = currentNode.next; 
      } 
      previousNode.next = currentNode.next; 
      currentNode.next = null; 
      numItems--; 

      return null; 

     } 

     /*if (numItems == 0) 

      return null; 
     } 
     else 
     { 
      Node temp = node1; 
      node1 = node1.next; 
      numItems--; 
      //if(node1 == null) 
       //lastNode = null; 
      return temp.entry; 

     }*/ 

    } 

    @Override 
    public boolean remove(T anItem) { 
     // TODO Auto-generated method stub 
     return false; 
    } 

    @Override 
    public void clear() { 


    } 

    @Override 
    public int getFrequencyOf(T anItem) { 
     // TODO Auto-generated method stub 
     return 0; 
    } 

    @Override 
    public boolean contains(T anItem) { 
     // TODO Auto-generated method stub 
     return false; 
    } 

    @Override 
    public T[] toArray() { 
     // Converts items in linked list to an array for easy displaying 
     @SuppressWarnings("unchecked") 
     T[] result = (T[])new Object [numItems]; 

     int i = 0; 
     Node currentNode = node1; 
     while((i<numItems)&&(currentNode != null)) 
     { 
      result[i] = currentNode.entry; 
      i++; 
      currentNode = currentNode.next; 
     } 
     return result; 
    } 




} 

이것은 내가 사용하는 테스트 프로그램입니다. "testRemove 내 생성자 클래스에서 내 '제거() 메소드를 호출하는 방법입니다

public class LinkedBagTest { 

    public static void main(String[] args) { 

     System.out.println ("Creating an empty bag."); 
      BagInterface <String> aBag = new LinkedBag <String>(); 
      displayBag (aBag); 
      testNumItems(aBag); 
      testRemove(aBag); 
      String [] contentsOfBag = {"A", "D", "B", "A", "C", "A", "D"}; 
      testAdd (aBag, contentsOfBag); 
      testNumItems(aBag); 
      testRemove(aBag); 
      displayBag (aBag); 
      testRemove(aBag); 
      displayBag (aBag); 
      //testIsFull(aBag, false); 


    } 
    private static void testAdd (BagInterface <String> aBag, 
       String [] content) 
     { 
      System.out.print ("Adding to the bag: "); 
      for (int index = 0 ; index < content.length ; index++) 
      { 
       aBag.add (content [index]); 
       System.out.print (content [index] + " "); 
      } // end for 
      System.out.println(); 
      displayBag (aBag); 
     } // end testAdd 

    private static void displayBag (BagInterface <String> aBag) 
     { 
      System.out.println ("The bag contains the following string(s):"); 
      Object [] bagArray = aBag.toArray(); 
      for (int index = 0 ; index < bagArray.length ; index++) 
      { 
       System.out.print (bagArray [index] + " "); 
      } // end for 
      System.out.println(); 
     } // end displayBag 

    private static void testIsFull (BagInterface <String> aBag, 
      boolean correctResult) 
    { 
     System.out.print ("\nTesting the method isFull with "); 
     if (correctResult) 
      System.out.println ("a full bag:"); 
     else 
      System.out.println ("a bag that is not full:"); 
     System.out.print ("isFull finds the bag "); 
     if (correctResult && aBag.isFull()) 
      System.out.println ("full: OK."); 
     else if (correctResult) 
      System.out.println ("not full, but it is full: ERROR."); 
     else if (!correctResult && aBag.isFull()) 
      System.out.println ("full, but it is not full: ERROR."); 
     else 
      System.out.println ("not full: OK."); 
    } // end testIsFull are here. 

    private static void testNumItems (BagInterface <String> aBag) 
    { 
     int items = aBag.getCurrentSize(); 
     System.out.println("There are " + items + " items in the bag"); 
    } 

    private static void testRemove (BagInterface <String> aBag) 
    { 
     aBag.remove(); 
     System.out.println("An Item was removed"); 

     testNumItems(aBag); 



    } 
} 
+0

알려주세요. 제대로 작동하지 않으면 가능한 경우 오류를 업데이트하십시오. – Jordon

답변

3

귀하의 널 점검이 형식이어야합니다. node1 == null 당신이 node1.equals(null)로 확인하고, 노드 1, 당신 실제로 널 'null로 자연스럽게 NullPointerException이 발생합니다 객체의 메소드를 호출하려고 다시.

+0

와우, 덕분에 도움이되었습니다. –

0

이 처음에, 당신 node1.equals(null) 대한 node1 = null 물건을 파괴하고, 당신이 equals 메소드를 호출하는 널 노드를 요구하는 왜 당신은 nullpointerexception이 될까요?

그래서 변경하고 넣어주세요 node1 == null