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

时间:2015-02-04 23:11:58

标签: 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;

  }

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

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

4 个答案:

答案 0 :(得分: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--;
    }

对于单链表,其中size是列表的当前大小,head - 头节点。

换句话说,您在所选元素上执行此类操作: illustrated removal of element in linked list http://oi60.tinypic.com/2ebcnq1.jpg

答案 1 :(得分:0)

如果要删除链接列表的所有元素,可以使用内置的clear()方法。

如果您不想使用该方法,则可以将头节点设置为null。垃圾收集器将负责其余的工作。

如果你想要一个删除方法,一次删除一件事,而你不关心它删除了什么,我建议你删除你找到的第一个元素。如果它在链接列表中,您只需将临时节点分配给头节点,将头节点重新分配给下一个节点,然后返回临时节点。

答案 2 :(得分:0)

看一下这个链接: link

同样是一个完整的例子:( 制作自己的链接和列表

(以下示例是一个链接列表,其中包含(链接)它的链接是一个点,例如A(50,3)。您可以将其转换为您想要的任何内容...)

链接

public class DoublePoint {

public double X;
public double Y;
public int LinkKey=0;
public DoublePoint nextLink; //keeps the nextLink

//Constructor
public DoublePoint(double Xpos,double Ypos,int key){
    X=Xpos;
    Y=Ypos;
    LinkKey=key;
}



public void printLinkKey(){
    System.out.println(LinkKey);
}


 //Return Link key

public String returnLinkKey(){

    return ""+LinkKey;
}



 public void changeContent(double x,double y){
      X=x;
    Y=y;

  }

public void ChangeLinkKey(int key){
    LinkKey=key;

}

  }

名单:

public class ListDoublePoints {

 public DoublePoint first;
 public int key; 
 public int totalLinks=0; 

public ListDoublePoints(){
    first=null;
    key=0;
}


//Insert


public void insertLink(double x,double y){
   DoublePoint newLink = new DoublePoint(x,y,key);
   newLink.nextLink=first;
   first=newLink;
   key++;
   totalLinks++;
}



//Find


public DoublePoint findLinkAt(int key){
    DoublePoint current=first;

 while(current.LinkKey!=key){ 
     if(current.nextLink==null)
         return null;
     else
        current=current.nextLink;

 }
 return current;

}


//Delete using Link key (similar with remove(int position) with ready java lists)


public String deleteLinkAt(int linkKey){

    DoublePoint current =first;
    DoublePoint previous=first;

    while(current.LinkKey !=linkKey){
        if(current.nextLink == null ){
            return "boom";}
        else
            previous=current;
            current=current.nextLink;
    }

    if(current==first)
        first=first.nextLink;
    else
        previous.nextLink=current.nextLink;

    --totalLinks;

    return "ok";
}


//Return


public int  LinksNumber(){
     return totalLinks;
}



//Print


public void displayList(){
   DoublePoint current=first;
  while(current!=null){
     current.displayLink();
     current=current.nextLink;
   }

}


 public void displayTheNumberOfLinks(){
    System.out.println(totalLinks);
  }

}

*如果您想要上述内容或

,请告诉我

只是为了处理java ready列表.. *

答案 3 :(得分:-2)

你的意思是这样吗???

代码

 private LinkedList<String> list = new LinkedList<>();

    private void fillList() {
        for (int i = 0; i < 10; i++) {
            list.add("Hello " + i);
        }
    }

    private void removeAllRandomly() {

        Random random = new Random();

        while (!list.isEmpty()) {
            int randomPosition = random.nextInt(list.size());
            String s = list.remove(randomPosition);
            System.out.println(String.format("Item on position: %s (%s) was removed", randomPosition, s));
        }

    }

结果

Item on position: 9 (Hello 9) was removed
Item on position: 1 (Hello 1) was removed
Item on position: 1 (Hello 2) was removed
Item on position: 2 (Hello 4) was removed
Item on position: 5 (Hello 8) was removed
Item on position: 0 (Hello 0) was removed
Item on position: 3 (Hello 7) was removed
Item on position: 1 (Hello 5) was removed
Item on position: 1 (Hello 6) was removed
Item on position: 0 (Hello 3) was removed