【问题标题】:Returning the head pointer of a linked list返回链表的头指针
【发布时间】:2015-07-01 08:43:32
【问题描述】:

为什么这段代码给出了正确的答案? 我正在返回一个指针。但是返回这个没有分段错误。这段代码的完整机制是什么? 谁能告诉input() 函数是如何工作的以及它如何返回链表的头部?

#include<bits/stdc++.h>
using namespace std;
typedef struct a{
int data;
struct a* next;
}link;
typedef link *node;

//Function to take input of linked list//

node input()
{
    int n,i;
    cout<<"Enter the size of the linked list\t";
    cin>>n;
    node g,header,rear;
    cout<<"Enter the elements\n";
    g=new link;
    g->next=NULL;
    cin>>g->data;
    header=g;
    rear=g;
    for(i=1;i<n;i++)
    {
        g=new link;
        cin>>g->data;
        g->next=NULL;
        rear->next=g;
        rear=g;
    }
    return header;
}

void output(node f)
{
    cout<<"Linked List ELEMENTS\n";
    //cout<<"\nThe content of linked list is\n";
    while(f!=NULL)
    {
        cout<<f->data<<"\t";
        f=f->next;
    }
}
int main()
{
node head,f;
head=input();
output(head);
return 0;
}

【问题讨论】:

  • 这个程序是你自己写的吗?
  • 为什么会出现分段错误?仅当您要返回指向局部变量的指针时,从函数返回指针才是问题。 header 是指向链表头的指针,它是使用new 动态分配的。

标签: c++ pointers linked-list


【解决方案1】:

每次返回指针时都不一定会出现分段错误。访问未分配的指针时发生分段错误。但是该函数首先使用new动态分配指针,然后访问并返回它。所以它可以正常工作。

input()函数

  1. 链表的大小(用户输入)

    int n,i;
    cout<<"Enter the size of the linked list\t";
    cin>>n;
    
  2. 头节点中列表的第一个元素(用户输入)

    node g,header,rear;
    cout<<"Enter the elements\n";
    g=new link;
    g->next=NULL;
    cin>>g->data;
    header=g;
    rear=g;
    
  3. 连接到头节点的列表的后续元素

    for(i=1;i<n;i++)
    {
        g=new link;
        cin>>g->data;
        g->next=NULL;
        rear->next=g;
        rear=g;
    }
    
  4. 返回的头节点

    return header;
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 2023-03-12
    • 2011-10-12
    • 2013-08-23
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多