Below is a recursive function I've written to add a node at the end of a linked list. Could anyone tell whether the function is correct or not?
下面是我编写的递归函数,用于在链表的末尾添加节点。谁能说出这个功能是否正确?
Node insertAtEnd(Node head, int data){
if(head.next == null){
Node temp= new Node(data);
head.next= temp;
return;
}
insertAtEnd(head.next, data);
}
There's already a class called Node which has been defined as below:
已经有一个名为Node的类,其定义如下:
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}
1 个解决方案
#1
2
Your method has a Node
return type, so you should return the new Node
:
您的方法具有Node返回类型,因此您应该返回新节点:
Node insertAtEnd(Node head, int data) {
if (head.next == null) {
Node temp= new Node(data);
head.next= temp;
return temp;
}
return insertAtEnd(head.next, data);
}
or
Node insertAtEnd(Node head, int data) {
if (head.next == null) {
head.next = new Node(data);
return head.next;
}
return insertAtEnd(head.next, data);
}
#1
2
Your method has a Node
return type, so you should return the new Node
:
您的方法具有Node返回类型,因此您应该返回新节点:
Node insertAtEnd(Node head, int data) {
if (head.next == null) {
Node temp= new Node(data);
head.next= temp;
return temp;
}
return insertAtEnd(head.next, data);
}
or
Node insertAtEnd(Node head, int data) {
if (head.next == null) {
head.next = new Node(data);
return head.next;
}
return insertAtEnd(head.next, data);
}