簡體   English   中英

從鏈接列表中刪除未指定的項目

[英]Removing unspecified item from linked list

我試圖從鏈表或“包”中刪除一個隨機節點。 請參考我的方法“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是從我的構造函數類調用我的'remove()'方法的方法

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);



     }
}

您的空檢查應采用以下格式: node1 == null 當您將其檢查為node1.equals(null) ,並且node1實際上為null時,您嘗試調用對象的方法,該方法為null並且自然會拋出NullPointerException。

這會破壞你的node1.equals(null) ,最初你的node1 = null ,並且你要求一個空節點調用equals方法,這就是你得到nullpointerexception

所以,請進行更改,並將node1 == null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM