Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, June 22, 2017

Sort a stack



class stacksort{
    public void insert(Stack<Integer> s,int x)
    {
        if(s.isEmpty() || x>s.peek())
        {
            s.push(x);
            return;
        }
        int temp=s.pop();
        insert(s,x);
        s.push(temp);
    }
public Stack<Integer> sort(Stack<Integer> s)
{
        if(!s.isEmpty())
        {
            int x=s.pop();
            sort(s);
            insert(s,x);
           
        }
        return s;
}
}

0 Comments:

Post a Comment

Stats