#include <iostream>
#include <cstddef>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
Node* insert(Node *head,int data)
{
if(head == NULL){
head = new Node(data);
return head;
}
else if(head->next == NULL){
Node *temp = new Node(data);
head->next = temp;
return head;
}
else{
insert(head->next, data);
}
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
mylist.display(head);
}
在为链表定义Node时,我们为什么要在类的前面放置一个指针
即如果我将其定义为Node* insert(Node *head,int data)
,那么Node insert(Node *head,int data)
语句会做什么以及会发生什么?
答案 0 :(得分:1)
将指针返回到列表的开头非常重要。空列表是head
指向NULL
(C)或nullptr
(C ++)的列表,两者均为零。当分配第一个元素的内存并添加节点时,返回该元素的地址,以便主函数可以跟踪列表的内存位置。
如果列表一次清空一个元素,最后对(假设的)delete
函数的最后一次调用将返回0,表示该列表再次为空。
如果我们使用Node insert(Node n, int data)
直接返回元素,该函数将返回节点的副本而不是实际节点。如果函数也被修改,那么可能可以工作,因为Node里面仍有指针,但通常使用指针。
如果您只是将函数的定义更改为Node insert(Node *n, int data)
,则所有可能的代码都不会编译,因为头部类型为Node *。