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

为什么链表为空时不插入数据?

如何解决为什么链表为空时不插入数据?

我用 C++ 为链表中的 Insert At Tail 函数编写了这段代码,但是当列表为空时,它不会插入数据。

这是它的图片:- https://i.stack.imgur.com/wKkXk.png

不知道为什么35到39行没有执行。

这是我的代码:-

#include <iostream>
using namespace std;

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

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

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

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

void Insert_At_Tail(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;
}

int main()
{
    node *head = NULL;
    int data;
    cout << "Enter the data: ";
    cin >> data;
    Insert_At_Tail(head,data);
    display(head);
    return 0;
}

这是我输出的快照:https://i.stack.imgur.com/FFGj6.png

解决方法

问题在于您没有在调用方处更改 head。要么参考头部

void insert_at_tail(node*& head,int data)

或者更好,返回新的头部:

void insert_at_tail(node *head,int data) {
    if (!head) return new node(data);
    node *tail = head;
    while (tail->next != NULL) tail = tail->next;
    tail->next = new node(data);
    return head;
}

这样称呼:

head = insert_at_tail(head,data);

更好的是将整个内容包装到一个类中,这样您就可以编写 linked_list.insert_at_tail(data) 并且只需要改变其成员。

,
void Insert_At_Tail(node *head,int data)

在 C++ 中,默认情况下,函数参数通过按值传递。此 head 参数是调用方传入的参数的副本

   head = new node(data);

这会设置新的 head 指针。这很好,但是因为这个 head 是原始参数的副本,所以这对调用者传入的 head 指针绝对没有任何作用。所有这些都是设置函数的 head 参数/变量。这对传递给此函数的 head 没有影响。

您可以执行以下两项操作之一(您的选择):

  1. 通过引用传递参数

  2. return 来自此函数的 head 指针的新值(如果 head 指针没有更改,则可以与传入的内容保持不变) ,并让调用者保存新的 head 指针。

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