我正在解决问题:https://www.codingninjas.com/studio/problems/introduction-to-linked-list_8144737?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf&leftPanelTab=0 在实现代码时,我收到错误消息“重复的类名:节点”。下面是我为此编写的代码:
class Node {
public static int data;
public static Node next;
Node()
{
this.data = 0;
this.next = null;
}
Node(int data)
{
this.data = data;
this.next = null;
}
Node(int data, Node next)
{
this.data = data;
this.next = next;
}
};
class implement {
public static Node head;
static Node addatend(int value){
Node temp=head;
Node add= new Node(value);
if(head==null){
head=add;
}
else{
while(temp.next!=null){
temp=temp.next;
}
temp.next=add;
}
return head;
}
public class Solution {
public static Node constructLL(int []arr) {
// Write your code here
Node ans=null;
implement z = new implement ();
for(int i=0;i<arr.length;i++){
int t=arr[i];
ans= z.addatend(t);
}
return ans;
}
}
谁能指出代码中的错误吗?
使用两个指针代替。
public static Node constructLL(int[] arr) {
Node head = null;
Node end = null;
for (int a : arr) {
if (head == null) {
head = new Node(a);
end = head;
}
else {
end.next = new Node(a);
end = end.next;
}
}
return head;
}