1

首先,提前感谢所有回复这篇文章的人。

其次,我浏览了所有其他帖子,但找不到任何对我有帮助的东西(抱歉,我是 C++ 新手)。

这是我的代码:

Node* Insert(Node *head,int data) //for linked lists
{
  Node* current = head;
  while(current -> next != NULL){
      current = current -> next;
  }
  cout << head -> data;
  Node *last = new Node();
  last -> data = data;
  last -> next = NULL;
  current -> next = last;
  return head;
}

似乎(通过行注释的反复试验)当前指针中下一个属性的访问似乎是问题所在,但我似乎无法弄清楚原因。Node 结构体有两个属性,*next(指向链表中的下一项)和 data(节点的数据)。

有什么想法吗?

linux用户

编辑:问题已解决 - 非常感谢所有留下评论的人!

遗憾的是,我无法使用**pHead取消引用解决方案,因为问题出在自动输入函数参数的网站上。然而,使用下面的评论,我制作了一个简单的程序,希望能为像我这样的其他初级 C++ 程序员详细说明这个问题:

Node* Insert(Node *head,int data)
{
    if(head == NULL){
        Node* last = new Node();
        last -> data = data;
        return last;
    }

    Node *current = head;
    while(current -> next != NULL){
        current = current -> next;
    }
    Node *last = new Node();
    last -> data = data;
    last -> next = NULL;
    current -> next = last;
    return head;  
}

问候,

linux用户

4

1 回答 1

1

这里最可能的问题是您不能使用Insert“跳转开始”您的列表:如果headNULL开始,循环将立即失败。此外,在第一次插入时,您将无法分配head.

要解决此问题,请将第一个参数从 更改Node *head为,将指针传递给头指针,并为函数Node **pHead代码添加额外的取消引用级别:Insert

Node* Insert(Node **pHead, int data)
{
    while(*pHead != NULL){
        pHead = &((*pHead)->next);
    }
    Node *last = new Node();
    last -> data = data;
    last -> next = NULL;
    *pHead = last;
    return last;
}

请注意,即使您将指针传递给Node设置为的指针,这种方法也将起作用NULL

Node *head = NULL;
Insert(&head, 1);
Insert(&head, 2);
Insert(&head, 3);
于 2013-11-10T02:09:36.920 回答