我一直在使用链接列表(出于学习目的,使用class)。我决定这次使用friend函数。该程序将生成2个链接列表对象,并调用friend void mergeAlternate(LL LL1, LL LL2);函数。 (LL是我班的名字)

mergeAlternate函数从链接列表中同时获取节点,并将其替换放置。
例如:

LL1:1-> 2-> 3

LL2:4-> 5-> 6

回答:1-> 4-> 2-> 5-> 3-> 6

这是我的代码::

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node *next;
    Node(int data) {
        this->data = data;
        this->next = NULL;
    }
};
class LL {
private:
    Node *head;
public:

    LL() : head(NULL) {
        createLL();
    }

    void printLL(Node *head) {
        if(head == NULL)
            head = this->head;
        Node *temp = head;
        while (temp != NULL) {
            cout << temp->data << "-->";
            temp = temp->next;
        }
        cout << "NULL" << endl;
    }

    void createLL() {
        head = new Node(2);
        head->next = new Node(7);
        head->next->next = new Node(8);
        head->next->next->next = new Node(1);
        head->next->next->next->next = new Node(4);
        head->next->next->next->next->next = new Node(9);
    }

    friend void mergeAlternate(LL LL1, LL LL2);

    ~LL() {
        Node *temp = NULL;
        while (head != NULL) {
            temp = head;
            head = head->next;
            delete temp;
        }
    }
};

void mergeAlternate(LL LL1, LL LL2) {
        Node *head1 = LL1.head, *head2 = LL2.head;
        Node *temp1, *temp2;
        while ((head1 != NULL) && (head2 != NULL)) {
            temp1 = head1->next;
            temp2 = head2->next;
            head1->next = head2;
            head2->next = temp1;
            if (temp1 == NULL)
                break;
            head1 = temp1;
            head2 = temp2;
        }
        if (head2 != NULL) {
            head1->next = head2;
        }
        LL2.head = NULL;
        LL1.printLL(LL1.head);
    }

int main() {
LL newLL, newLL2;
    newLL2.printLL(NULL);
    mergeAlternate(newLL, newLL2);
    newLL2.printLL(NULL);
}


我有一个用于打印链表的printLL函数。

问题是在我的mergeAlternate中,我按值传递了2个链接列表。因此,我希望链接列表newLLnewLL2保持不变。但是,在main中,当执行mergeAlternate后,当我打印链接列表时,会出现运行时错误,并且会打印类似的内容。

155672576-->155672672-->155672592-->155672688-->155672608-->155672704-->155672624-->155672720-->155672640-->155672736-->155672656-->NULL

虽然我希望相同的输入链接列表可以再次打印。为什么会这样?有什么我想念的吗?谢谢你的帮助 :)

ideone链接:: http://ideone.com/apRCTw

最佳答案

函数void mergeAlternate(LL LL1, LL LL2)创建两个新的局部变量LLLL2,它们的成员head也将指向newLLnewLL2分别指向的相同内存地址。因为LL1LL2是函数的局部变量,所以当函数结束时,将调用它们各自的析构函数。根据您的析构函数定义:

~LL() {
    Node *temp = NULL;
    while (head != NULL) {
        temp = head;
        head = head->next;
        delete temp;
    }
}


它将取消分配NodesLL1LL2,但是,因为它们与newLLnewLL2是相同的内存地址,这意味着当函数结束时,这最后两个对象将具有垃圾值。在其成员head和后续引用中,这将在尝试访问其值时导致错误。

关于c++ - 链接列表中的运行时错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31094602/

10-12 15:04
查看更多