返回链表的头指针

Returning the head pointer of a linked list

本文关键字:指针 链表 返回      更新时间:2023-10-16

为什么这段代码给出了正确的答案?我正在返回一个指针。但是,在返回这个过程中没有分段错误。本准则的完整机制是什么?有人能告诉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 listt";
    cin>>n;
    node g,header,rear;
    cout<<"Enter the elementsn";
    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 ELEMENTSn";
    //cout<<"nThe content of linked list isn";
    while(f!=NULL)
    {
        cout<<f->data<<"t";
        f=f->next;
    }
}
int main()
{
node head,f;
head=input();
output(head);
return 0;
}

每次返回指针时都必须得到分段错误。访问未分配的指针时会发生分段错误。但函数首先使用new动态分配指针,然后访问并返回指针,因此它可以正常工作。

input()功能

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

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

    node g,header,rear;
    cout<<"Enter the elementsn";
    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;