小编the*_*563的帖子

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

我正在尝试为一个类做一个赋值,我使用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 …
Run Code Online (Sandbox Code Playgroud)

java linked-list

2
推荐指数
1
解决办法
3553
查看次数

标签 统计

java ×1

linked-list ×1