返回链表的头指针
Returning the head pointer of a linked list
为什么这段代码给出了正确的答案?我正在返回一个指针。但是,在返回这个过程中没有分段错误。本准则的完整机制是什么?有人能告诉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()
功能
-
链接列表的大小(用户输入)
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;
相关文章:
- C++,指针数组,指向双链表中的条目
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 链表指针问题
- 将链表转换为指针数组时出错
- 如何实现容纳整数和无效指针的双向链表?
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 为什么我在空指针错误(链表)中获取成员访问权限
- 链表删除功能的单指针 // 是可能的
- 如何深度复制链表对象指针
- 链表 - 使用后面的指针在末尾插入
- 链表和指针在C++中的点
- 未分配被释放的指针(将堆栈实现为链表时)
- 使用双指针和递归反转链表
- 使用函数引用指向节点的指针删除链表中的节点?
- 使用 XOR 操作仅使用 2 个指针反转链表
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 指针永远不会在链表深层复制构造函数中达到 null
- 链表指针赋值为什么我们不能直接将尾巴分配给 temp 而不是尾巴>尾巴下一个
- 如何从文件读取到动态分配的指向结构的指针链表中?
- C++指针链表