改组链表Java [英] Shuffling an linked list Java

查看:42
本文介绍了改组链表Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难使用伪代码进行改组算法并将其转换为有效的Java代码.我正在尝试随机播放链接列表.总体而言,该方法采用链接列表的开头的指针,并随机返回指向同一列表的开头的指针.我想使用我创建的getLength和getItem方法.

I'm having a very hard time using a pseudo code for the shuffling algorithm and turning it to a working java code. I'm attempting to shuffle a linked list. Overall the method takes the pointer of the head of the linked list and returns a pointer to the head of the same list randomly. I want to use a getLength and getItem method I've created.

public static ListElement shuffle(ListElement head){
  head = head.getLength();
  ListElement head2= null;
  while( head == null) {
    int random = (int) Math.random() *  n;
    for(int i=0;i<random;i++){
        head= head.getNext();
    }
  }
  return head;    
}

伪代码:

A list L of length n
A new list R, empty
while L is not empty
   pick a random k 
   such that 0<=k<= (length L)
   remove the kth element of L
      call it e
   prepend e to R

推荐答案

我只是稍微重写一下代码,使其遵循伪代码.

I just rewrite the code a bit so that it follows the pseudo code.

ListElement head2 = null;
int length = head.getLength();

while (head != null) {
    int k = (int) Math.random() * length;

    // Assume there is function deleteAt(index) that removes
    // the element at specified index and returns the deleted
    // element
    ListElement e = head.deleteAt(k);
    // Although I can just give the implementation - I'll leave this
    // as exercise.

    // You can have a function that add element to front
    // head2.addFront(e);
    e.setNext(head2);
    head2 = e;

    // Instead of querying the length again
    // decrement the length
    length--;
}
return head;

这篇关于改组链表Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆