随机合并两个链表

时间:2014-02-13 03:39:53

标签: c++ recursion linked-list shuffle

我首先要说的是我已经寻找并尝试了几种不同的解决方案而没有运气。我已经做了很长时间了,所以任何帮助都会非常感激。

该任务是随机播放代表一副牌的链表。我得到了所有的方法声明,并被告知我只允许使用递归。我已经以一切可能的方式解决了这个问题而没有任何运气。

基本上我们被告知使用的策略是将链表拆分为2,将两个列表混合(通过递归调用shuffle方法),然后将混洗后的列表合并在一起。

您可能需要了解的一些内容:

  • LLN =链接列表节点
  • len =“此”列表的长度
  • b =将“this”与
  • 合并的列表
  • blen =“b”列表的长度

此代码返回一个空列表,我看不清楚原因(显然)。 LLN-> shuffle()应该返回混洗列表的头部。现在它正在返回一个空列表。

LLN * LLN::merge(int len, LLN *b, int blen) {
    //cout << "len: " << len << ", blen: " << blen << endl;

    if (len == 0) return b;
    if (blen == 0) return this;

    int r = rand() % (len + blen) + 1; // between 1 and (len + blen)

    if (r <= len) {
        if (next)
            next = next->merge(len - 1, b, blen);
        else
            next = b;

        return this;
    } else {
        if (b->getnext())
            b->setnext(b->getnext()->merge(blen - 1, this, len));
        else
            b->setnext(this);

        return b;
    }
}

LLN *LLN::shuffle(int len) {
    if (len == 1)
        return this;

    LLN *tmp = split();

    int thisLength = (len + 1) / 2; // for an odd numbered length, "this" list is 1 node larger
    int tmpLength = len / 2;

    shuffle(thisLength);
    tmp = tmp->shuffle(tmpLength);

    return merge(thisLength, tmp, tmpLength);
}

这是调用方法的方法。

void LL::shuffle() {
    if (head != NULL)
        head = head->shuffle(size);
}

使用标准52卡(每个卡作为节点)初始化LL(链接列表)对象。

如果您还有其他需要,请告诉我。

非常感谢!

2 个答案:

答案 0 :(得分:0)

shuffle(thisLength);
tmp = tmp->shuffle(tmpLength);

return merge(thisLength, tmp, tmpLength);

这里 shuffle(thisLength)的返回值可能 这个,所以我们应该这样做

first = shuffle(thisLength);
tmp = tmp->shuffle(tmpLength);

return first->merge(thisLength, tmp, tmpLength);

答案 1 :(得分:0)

我能够在教授的帮助下找出问题所在。原来我的错误是在我的split()方法的基本情况。有了这个修复一切正常。我也应用了查理的建议。

相关问题