微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的链表打印地址而不是打印值?

如何解决为什么我的链表打印地址而不是打印值?

这是合并两个已排序链表(按排序顺序)的代码

我的代码是打印地址而不是打印排序列表。 我无法理解问题出在哪里。

这是我的代码

#include <iostream>
using namespace std;

class node
{
public:
    int data;
    node *next;

    node(int d)
    {
        data = d;
        next = NULL;
    }
};

node *Merge(node *head1,node *head2)
{
    if (head1 == NULL)
    {
        return head2;
    }

    if (head2 == NULL)
    {
        return head1;
    }

    node *c = NULL;
    if (head1->data < head2->data)
    {
        c = head1;
        c->next = Merge(head1->next,head2);
    }
    else
    {
        c = head2;
        c->next = Merge(head1,head2->next);
    }
    return c;
}

void InsertAtTail(node *&head,int data)
{
    if (head == NULL)
    {
        head = new node(data);
        return;
    }

    node *tail = head;
    while (tail->next != NULL)
    {
        tail = tail->next;
    }
    tail->next = new node(data);
    return;
}

void display(node *head)
{
    if (head == NULL)
    {
        cout << "The Linked List is empty !!";
        return;
    }

    while (head != NULL)
    {
        cout << head->data << " -> ";
        head = head->next;
    }
    cout << endl;
}

int main()
{
    node *head1 = NULL;
    node *head2 = NULL;
    int n1,n2,data;
    cout << "Creating 1st Linked List: " << endl;
    cout << "Enter the number of nodes you want to enter: ";
    cin >> n1;
    for (int i = 0; i < n1; i++)
    {
        cout << "Enter the data: ";
        cin >> data;
        InsertAtTail(head1,data);
    }

    cout << "Creating 2nd Linked List: " << endl;
    cout << "Enter the number of nodes you want to enter: ";
    cin >> n2;
    for (int i = 0; i < n2; i++)
    {
        cout << "Enter the data: ";
        cin >> data;
        InsertAtTail(head2,data);
    }

    display(head1);
    display(head2);

    node *NewNode = NULL;
    NewNode = Merge(head1,head2);
    cout << "The sorted list is: " << endl;
    cout << NewNode << endl;
    return 0;
}

这是我输出的屏幕截图: https://i.stack.imgur.com/dUv7A.png

所有其他功能都正常工作。但是在调用 Merge 函数之后,它是打印地址(十六进制)值而不是打印新的排序链表。

解决方法

看来您只需要将 cout << NewNode << endl; 替换为:display(NewNode);

,

最后一行代码 cout << NewNode << endl; 将打印地址,因为 NewNode 是一个指针,而不是调用 display(NewNode) 来打印所有节点。

,

我刚刚将 cout << NewNode << endl; 替换为 cout << display(NewNode) << endl;

而且,它正在工作。

代码很好。 小心那些愚蠢的错误。一切顺利。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。