Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Recursive Sum of Linked list node values

   private static int recursiveSum(Node head) {
        //base case
        if (head.next == null) {
            return head.value;
        }
        //general case
        return head.value + recursiveSum(head.next);
    }

2 comments:

  1. how do you print the result?

    ReplyDelete
    Replies
    1. int n = recursiveSum(Linkedlist.head());
      System.out.println("Total sum = " +n);

      private static int recursiveSum(Node head) {
      //base case
      if (head.next == null) {
      return head.value;
      }
      //general case
      return head.value + recursiveSum(head.next);
      }

      Delete

Search 24 Bytes