Thread: Recursive Function to Add values in a list

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    2

    Recursive Function to Add values in a list

    Hello everyone,

    I am trying to implement a function that goes through a doubly linked list of integer values and adds the values recursively.

    My class consists of a Node class that has the private data set with right and left pointers and the value. The public section consists of getters for the value and the left and right pointers.

    Now Assuming that the list is already populated. This is the function that I have implemented so far to recursively add the values from the list but I am not sure if this is a proper implementation of recursion?

    I am trying to add the value of the current node with the sum of the rest of the list. Any hints of suggestion is very much appreciated. Thanks in advance for your help!

    Code:
    int sum(Node* list)
    {
        if (list==NULL) return 0;
        else 
        {
            while (list!=NULL)
            return list->getValue()+sum(list->getRight());
        }
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    It is, if you remove while (list!=NULL)

    Not that it matters, because the return statement makes it totally ineffective to begin with.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. c program that accepts and executes commands?
    By Cimposter in forum C Programming
    Replies: 3
    Last Post: 09-30-2009, 02:58 PM
  2. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. compiler build error
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2003, 10:16 AM
  5. linked list recursive function spaghetti
    By ... in forum C++ Programming
    Replies: 4
    Last Post: 09-02-2003, 02:53 PM