简体   繁体   English

从链接列表中删除未指定的项目

[英]Removing unspecified item from linked list

I'm trying to remove a random Node from a linked list or "bag" so to speak. 我试图从链表或“包”中删除一个随机节点。 Please refer to my method "T remove()". 请参考我的方法“T remove()”。 I can't get it to remove the node without it throwing a NullPointerException error. 我不能让它删除节点而不抛出NullPointerException错误。

First I have the method return a NULL if there is nothing in the list to begin with. 首先,如果列表中没有任何内容,则首先返回NULL。 If a node exists then I loop through the numberofNodes, find a random one and try to delete that node. 如果存在节点,那么我遍历numberofNodes,找到一个随机节点并尝试删除该节点。 I make a node that temporarily points to the data of the next node and have the previous node point to the node after the currentNode as if it doesn't exist. 我创建了一个临时指向下一个节点数据的节点,并让前一个节点指向currentNode之后的节点,就好像它不存在一样。

Is my logic wrong? 我的逻辑错了吗?

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




}

This is the test program I use. 这是我使用的测试程序。 "testRemove is the method that calls my 'remove()' method from my constructor class “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);



     }
}

Your null checks should be in this format: node1 == null . 您的空检查应采用以下格式: node1 == null When you check it as node1.equals(null) , and node1 is actually null, you're trying to call a method of an object, which is null and will naturally throw a NullPointerException. 当您将其检查为node1.equals(null) ,并且node1实际上为null时,您尝试调用对象的方法,该方法为null并且自然会抛出NullPointerException。

This is ruining things for you node1.equals(null) , initially your node1 = null , and you are asking a null node to call equals method, which is why you are getting nullpointerexception . 这会破坏你的node1.equals(null) ,最初你的node1 = null ,并且你要求一个空节点调用equals方法,这就是你得到nullpointerexception

So, please make changes, and put node1 == null 所以,请进行更改,并将node1 == null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM