如何从链表中删除随机选择的元素?

the*_*563 2 java linked-list

我正在尝试为一个类做一个赋值,我使用String Bag类的remove方法返回链表的所有元素,一次一个,然后从列表中删除该元素.我有一个开始,但我无法弄清楚到底该怎么做.有人可以帮忙吗?

 public String remove()
  {
      Random rand = new Random();
      int randNum = rand.nextInt(numItems);
      //generate random number
      int count = 0;
      String get;
      currNode = firstNode;
      //temporary node to get String from

      while(count < randNum)
      {
          currNode = currNode.getLink();  
          count++;
      }
      //randomly select node to get String from
      get = currNode.getInfo();

      numItems--;
      if(numItems == 0)
      {
          firstNode = null;
      }
      //decrement the number of items in the bag and make the first node
      //null when it reaches 0
      return get;

  }
Run Code Online (Sandbox Code Playgroud)

编辑:这是应用程序级别:

public class StringBagTest 
{

 public static void main(String[] args) 
 {          
    LLStringBag bag = new LLStringBag();
    bag.insert("Hat");
    bag.insert("Shirt");
    bag.insert("Pants");
    bag.insert("Shoes");
    //insert 4 strings into the list
    while(!bag.isEmpty())
    {
    System.out.println(bag.remove());
    }
    //randomly removes all contents of list
  }
}
Run Code Online (Sandbox Code Playgroud)

Dmy*_*tro 5

如果你想通过索引删除随机选择的元素,那么它看起来像这样:

public void removeRandomElement() {
        int index = new Random().nextInt(size);
        Node current = head;
        Node prev = head;
        for (int i = 0; i < index; i++) {
            prev = current;
            current = current.next;
        }
        prev.next = current.next;
        current.next = null;
        size--;
    }
Run Code Online (Sandbox Code Playgroud)

对于单链表,列表的size当前大小,head- 头节点.

换句话说,你在所选元素上做了类似的事情: 链接列表中元素的删除http://oi60.tinypic.com/2ebcnq1.jpg