【问题标题】:How to create a node using the structure definition if the integer value is passed to a function?如果将整数值传递给函数,如何使用结构定义创建节点?
【发布时间】:2021-03-08 17:12:50
【问题描述】:

结构的定义如下。


//Structure of the linked list node is as follows:

struct Node {
  
    int data;
    struct Node* next;

    Node(int x) {
        data = x;
        next = NULL;
    }

};

我必须完成我以这种方式完成的这个功能。我正在尝试使用函数定义中传递的 newData 参数创建一个节点。但它显示了我在下面附加的错误。

// function inserts the data in front of the list
                                                                                                
Node* insertAtBegining(Node *head, int newData) {   
    //Your code here

    struct Node* newNode(newData);
    struct Node* temp;

    temp=head;
    head=newNode;
    newNode->next=temp;

}

我通过将 newData 作为参数传递给struct Node *newNode(newData); 创建节点时收到此错误

在函数Node* insertAtBegining(Node*, int)

prog.cpp:67:32: 错误:从 int 到 Node* [-fpermissive] 的无效转换

结构节点 *newNode(newData);

感谢您的帮助。

【问题讨论】:

  • 顺便说一句,在 C++ 中,定义变量(或指针)时不需要 struct 关键字。
  • 你的功能在于。函数签名说函数返回Node *,但你的函数什么也不返回。将返回类型更改为void(表示没有返回值)或返回Node * 变量。

标签: c++ linked-list singly-linked-list


【解决方案1】:

您的构造函数返回一个 Node,而不是 Node*,因此当您尝试初始化 newNode 时,编译器会认为您正在尝试使用 int 创建一个指针。相反,你应该期待你的构造函数给你一个节点:

Node newNode(newData);

【讨论】:

  • 我了解解决方案。非常感谢您宝贵的时间。
【解决方案2】:

您的insertAtBegining() 实现需要创建一个新的Node 对象。你没有那样做。在老师的Your code here 评论之后,您的尝试定义了一个“Node 指针”变量(其类型为Node*),但您的尝试尚未将其初始化为任何Node 对象(数据本来是传递给对象的构造函数与对象本身不同)。

此外,您不需要像我们这些老家伙过去使用老式 C 代码那样重复 struct

最后,您似乎还希望将列表的新头节点返回给函数的调用者,但不清楚您希望如何实现。有两种方法。您的代码似乎倾向于以相同的head 参数返回新的头部。在这种情况下,它应该如下所示:

void insertAtBegining(Node** head, int newData)
{
//Your code here
    Node* newNode = new Node(newData);
    Node* temp;
    temp = *head;
    *head = newNode;
    newNode->next = temp;
}

(通过对代码进行适当的更改,head 参数也可以是“对Node* 的引用”,而不是“指向Node* 的指针”。)

第二个选项(保持老师推荐的函数签名)是通过函数的返回值返回新的头部:

Node* insertAtBegining(Node* head, int newData)
{
//Your code here
    Node* newNode = new Node(newData);
    newNode->next = head;
    return newNode;
}

【讨论】:

  • 感谢您的详细解决方案。我实际上是结构和链表概念的新手,所以我对这些概念没有太多了解。但我已经理解你的解决方案。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2011-01-12
相关资源
最近更新 更多