C ++ Struct指针段错误

时间:2013-11-10 02:04:38

标签: c++ pointers struct

首先,感谢所有回复此帖的人。

其次,我查看了所有其他帖子,找不到任何有帮助的帖子(道歉,我是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(节点的数据)。

有关正在发生的事情的任何想法?

linuxuser

编辑:问题解决了 - 非常感谢所有发表评论的人!

可悲的是,我无法使用**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;  
}

此致

linuxuser

1 个答案:

答案 0 :(得分:1)

此处最有可能的问题是,您无法使用Insert“快速启动”您的列表:如果head开始为NULL,则循环将失败远。此外,在第一次插入时,您将无法分配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的{​​{1}}指针,此方法也会起作用:

NULL
相关问题