简体   繁体   English

一种递归算法,用于添加非哑头单向线性列表的所有元素。 只有列表的头部将作为参数给出

[英]A recursive algorithm to add all the elements of a non-dummy headed singly linked linear list. Only head of the list will be given as parameter

I am facing a run-time error while adding the elements of a singly linked list.我在添加单向链表的元素时遇到运行时错误。 I have po enter image description here sted the picture of the error.I am attaching my codes here:我在此处输入图像描述以插入错误图片。我在此处附上我的代码:

    public class Node{
      Node next;
      int a=0;
    
        public Node (int e, Node n){
          a =e;
          next =n;
      }}
    
    
    public class Question6{
      static int sum=0;
      public static void main(String[]args){
    
        Node head=null;
        
        Node n5= new Node(5,null);
        Node n4= new Node(4,n5);
        Node n3= new Node(3,n4);
        Node n2= new Node(2,n3);
        Node n1= new Node(1,n2);
        
        head=n1;
        sum =add(head);   
      }
      public static int add(Node head){
        if(head==null){
          return sum;
        }
        else{
          sum=sum + head.a;
          head=head.next;
          add(head);
        }
        return sum;
      }
    }

It looks like something wrong with your compiler.看起来你的编译器有问题。 Error in the image says that it can not find init method in class Node .图像中的错误表示在类Node找不到 init 方法。 Try to add empty init method (curly brackets) in class Node :尝试在类Node添加空的 init 方法(大括号):

class Node{
        Node next;
        int a = 0;

        {}

        public Node(int e, Node n) {
            a = e;
            next = n;
        }
}

First of all your code is not a real recursion, because of you use external static variable .首先,您的代码不是real递归,因为您使用了external static variable

public static int sum(Node head) {
    return sum(head, 0);
}

private static int sum(Node node, int sum) {
    return node == null ? sum : sum(node.next, sum + node.a);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM