【问题标题】:Why linked list is not inserting data when it is empty? [duplicate]为什么链表为空时不插入数据? [复制]
【发布时间】:2021-05-15 13:51:32
【问题描述】:

我在 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

【问题讨论】:

    标签: c++ data-structures linked-list


    【解决方案1】:
    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 指针。

    【讨论】:

      【解决方案2】:

      问题是你没有在调用者处更改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) 并且只需要改变它的成员。

      【讨论】:

        猜你喜欢
        • 2016-06-18
        • 2014-09-10
        • 2020-09-17
        • 1970-01-01
        • 1970-01-01
        • 2017-02-11
        • 2014-05-29
        • 2020-08-02
        • 2021-07-05
        相关资源
        最近更新 更多