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);
    }

3 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
  2. Please let me know if my code is correct or not :
    SumofValues(Node head)
    {
    int sum=0;
    if(head==null) { return 0;}
    if(head.next==null)
    { sum = sum + head.data;
    return sum;
    }
    else
    {
    sum = sum + SumofValues(head.next);
    return sum;
    }

    ReplyDelete

Search 24 Bytes