0

I am using a merge sort algorithm to sort a linked list

void node::merge_sort()
{
    if (head == NULL || head->next == NULL)
    {
        return;
    }
    node *p = new node;
    node *q = new node;
    this->divide(&p, &q);
    p->merge_sort();
    q->merge_sort();
    this=merge_lists(p, q);
}

but I have to change the object inside this method due to which I typed this=merge_lists(p,q). But this is giving an error saying nolvalue. Is there any alternative way?

The divide function is used to divide the list into two parts and store them in p and q.

4

1 回答 1

1

不,您不能重新分配this. 类比是,如果我走到你面前说“你现在是那边的那个身体”。您的回答将是“这甚至没有意义”。你是对的。您要做的是更改当前对象的状态,而不是完全替换它。

此外,这里没有理由分配动态对象。不要那样做。这会使您的代码变慢并且更容易出错。实际上,您的界面似乎根本不需要指针

void node::merge_sort()
{
    if (head == NULL || head->next == NULL)
    {
        return;
    }
    node left, right;
    divide(left, right);
    left.merge_sort();
    right.merge_sort();
    *this = merge_lists(left, right); //this line is the key to answering to your question
}

然后从以下位置更改您的函数签名:

void node::divide(node** left, node** right);
node merge_lists(node* left, node* right);
node& node::operator=(const node& right_hand_side);

void node::divide(node& left, node& right);
node merge_lists(node& left, node* right);
node& node::operator=(const node& right_hand_side);
node& node::operator=(node&& right_hand_side); //along with this line

这里的键是*this =,它重新分配当前对象持有的值,而不是试图替换当前对象的存在。此外,移动赋值运算符使其快速。

于 2013-08-22T17:05:38.653 回答