#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    1
    Rep Power
    0

    How to find the even numbers in a given linked list by using recursion?


    I could do better things in the first day of the year but i'm trying to implement the linked lists and recursion together.

    I just thought that how I can achieve to write a function that calculates the even numbers in a linked list with recursion.

    This is a draft of the recursion code i know this is wrong but how should I implement the code?

    void List:: findingEvens(Node* n){
    if(n == NULL)
    return;
    else
    if(n-> data % 2 != 0)
    findingEvens(n-> next);
    else
    findingEvents(n-> next);
    }
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,905
    Rep Power
    481
    Recursively traversing a singly linked list is not sane.

    Misspelling evens as events doesn't look useful.

    if (condition) same_action;
    else same_action;

    is pathetic.

    Happy new year. Mine's not starting happy, and I'm passing it along. Sorry.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2009
    Posts
    149
    Rep Power
    37
    how about this pseudocode:

    Code:
    int findingEvens(node L, int E)
    
    	if(null L)
    		return 0;
    		
    	if(L->element is even)
    		if(null L->next)
    			return E + 1
    		else
    			return findingEvens(L->next, E + 1)
    	else
    		if(null L->next)
    			return E
    		else
    			return findingEvens(L->next, E)

IMN logo majestic logo threadwatch logo seochat tools logo