Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Wednesday, December 2, 2015

Find Factorial of a Number

// Recursive approach
    public int getFactorialRecursive(int n)    {
        if(n==0)    return 1;
        else
            return n * getFactorial(n-1);
    }

// Non Recursive approach
    public int getFactorial(int n)    {
        int factorial=1;
        if(n==0) return factorial;
        while(n!=0)    {
            factorial=factorial*n;
            n--;
        }
        return factorial;
    }

Wednesday, November 25, 2015

Reverse a Single Linked List in Java using Recursion

You can refer for Linked List in Java program here: link

This is a program to reverse a linked list using recursion.
    public String reverseList()    {
        return reverseList(this, new StringBuffer()).toString();
    }
    private StringBuffer reverseList(LinkedList L, StringBuffer sb)    {
        if(L!=null)    {
            reverseList(L.next, sb);
            sb.append(L.data).append(", ");
        }
        return sb;
    }
UA-39217154-2