【问题标题】:Bag remove() method袋子 remove() 方法
【发布时间】:2018-10-16 16:51:19
【问题描述】:

我被赋予了这样的 Bag 类

    import java.util.Iterator;
    import java.util.NoSuchElementException;

    public class Bag<Item> implements Iterable<Item> {

    private int N;               // number of elements in bag
    private Node<Item> first;    // beginning of bag

    // helper linked list class
    private class Node<Item> {
    private Item item;
    private Node<Item> next;
    }

    /**
    * Initializes an empty bag.
     */
    public Bag() {
    first = null;
    N = 0;
    }

    /**
     * Is this bag empty?
    * @return true if this bag is empty; false otherwise
     */
    public boolean isEmpty() {
    return first == null;
    }

    /**
     * Returns the number of items in this bag.
     * @return the number of items in this bag
     */
    public int size() {
    return N;
    }

    /**
     * Adds the item to this bag.
     * @param item the item to add to this bag
     */
    public void add(Item item) {
    Node<Item> oldfirst = first;
    first = new Node<Item>();
    first.item = item;
    first.next = oldfirst;
    n++;
}

    public void remove(Item item){ 
    // currentNode is the reference to the first node in the list and to the Item
    Node<Item> currentNode = first; 
    // if items equals the first node in the list, then first = currentNode.next which will make the first item 
    Node<Item> temp = currentNode;
    while(temp.next != null){
        temp = currentNode;
        if(item.equals(currentNode.item)){
            currentNode = currentNode.next;
            temp.next = currentNode;
            break;
        }else{
            currentNode = currentNode.next;
        }
    }
    N--; 
}

/**
 * Returns an iterator that iterates over the items in the bag in arbitrary order.
 * @return an iterator that iterates over the items in the bag in arbitrary order
 */
public ListIterator<Item> iterator()  {
    return new ListIterator<Item>(first);  
}

// an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
    private Node<Item> current;

    public ListIterator(Node<Item> first) {
        current = first;
    }

    public boolean hasNext()  { return current != null;                     }
    public void remove()      { throw new UnsupportedOperationException();  }

    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        Item item = current.item;
        current = current.next; 
        return item;
    }
}

可以看出,remove() 方法是可选的,因此它不包含算法。

我是这样写remove方法的:

public void remove(Item item)      { 
        Node<Item> currentNode = (Node<Item>) first;
        Node<Item> previousNode = null;
        while(currentNode != null){
            if(item.equals(currentNode.item)){
                if(previousNode  == null) {
                  first = (Node<Item>) currentNode.next;
                }
                else {
                  previousNode.next = currentNode.next;
                }
                n--;
            }
            else {
              previousNode = currentNode;
            }
            currentNode = currentNode.next;
        }

    }

然而,

first = (Node<Item>) currentNode.next;

这一行给出了一个“类型不匹配:无法从 Bag.Node 转换为 Bag.Node”的错误,这让我很困惑。

应该做些什么来克服这个错误,或者我的删除方法中是否缺少部分?

【问题讨论】:

  • 代码中有n个和N个变量,大小写应该一样

标签: java algorithm data-structures linked-list bag


【解决方案1】:
public class Bag<Item> implements Iterable<Item> {
  // ...
  private class Node<Item> {
    // ...
  }
  // ...
}

这定义了两个不同的类型变量,名称均为Item

如果您希望Node 的实例使用与Bag 的包含实例相同的类型变量,请删除Node 上的&lt;Item&gt;

private class Node {

【讨论】:

  • 我也试过了,但是“私有项目项目”变量给出了一个错误“无法对非静态类型项目进行静态引用”
  • @FikretEfeDoğanay 考虑到您在此代码中不使用 static,我对此表示怀疑。如果是private static class Node&lt;Item&gt;,我会相信。您确定这是您要运行的确切代码吗?
  • 是的,你是对的!我忘了删除 Node 类中的静态字段。非常感谢!
【解决方案2】:

我以这种方式克服了这个问题。

   public void removeAllOccurences(Item item){ 

   Node<Item> currentNode = first;

   Bag<Item> b = new Bag<Item>();
   Bag<Item> reverseB = new Bag<Item>();

   Node<Item> previous = new Node<Item>();

        if(item.equals(first.item)){

                first = currentNode.next;
                N--;
                currentNode = currentNode.next;
                }

            previous.item = currentNode.item;

            b.add(previous.item);

            currentNode = currentNode.next;

            while(currentNode != null){

                if(item.equals(currentNode.item))
                {
                    previous.item = previous.item;
                        N--;

                } else{

                        previous.item = currentNode.item;
                        b.add(previous.item);

                }


                currentNode = currentNode.next;


            }

            for(Item i: b)
                reverseB.add(i);

        this.first = reverseB.first;

}

如果你想测试...

public static void main(String[] args) {

    Bag<Integer> b = new Bag<Integer>();
    Random rm = new Random();

    for(int i =0; i < 10; i++)
        b.add(rm.nextInt(3));

    System.out.println("Bag before removing op: ");
    for(Integer i: b)
        System.out.print(" "+ i);

    System.out.println("\nBag size BEFORE: "+b.size());

    b.removeAllOccurences(2);

    System.out.println("\nBag after removing op: ");
    for(Integer i: b)
        System.out.print(" "+ i);
    System.out.println("\nBag size AFTER: "+b.size());

}

输出删除所有出现的 2:

 0 2 2 0 1 1 0 0 0 2
Bag size BEFORE: 10

Bag after removing op: 
 0 0 1 1 0 0 0
Bag size AFTER: 7

【讨论】:

    猜你喜欢
    • 2012-07-17
    • 2012-08-21
    • 2013-09-12
    • 2014-03-16
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多