-3

Here are the constraints :

  1. Only STL must be used for stack creation (do not use struct to create stack)
  2. Sort the stack without using any loops

I have figured out the solution with constraint 2. But when I create a stack using STL to satisfy constraint 1, the stack is not getting sorted and the output is just same as the input.

Expected Output : 5 4 3 2 1 My Output : 1 2 4 3 5

Below is the code :

#include<iostream>
#include<stack>
using namespace std;

void SortedInsert(stack<int> S,int x)
{
    if(S.empty() || x > S.top())
        S.push(x);
    else
    {
        int temp = S.top();
        S.pop();
        SortedInsert(S,x);
        S.push(temp);
    }

}


void StackSort(stack<int> S)
{
    if(!S.empty())
    {   
        int x = S.top();
        S.pop();        
        StackSort(S);
        SortedInsert(S,x);
    }
}

void main()
{
    int arr[5] = {1,2,4,3,5};

    stack<int> S;

    for(int i=4 ; i>=0 ; i--)
        S.push(arr[i]);

    StackSort(S);

    while(!S.empty())
    {
        cout<<S.top()<<" ";
        S.pop();
    }

    cin.get();
}
Prasath Govind
  • 720
  • 2
  • 10
  • 30

2 Answers2

2

Pass the stack by reference or as a pointer.

Example for "by reference":

void StackSort(stack<int> &S)
{
    if(!S.empty())
    {   
        int x = S.top();
        S.pop();        
        StackSort(S);
        SortedInsert(S,x);
    }
}

Call it like this: StackSort(S);

Example for "by pointer":

void StackSort(stack<int> *S)
{
    if(!S->empty())
    {   
        int x = S->top();
        S->pop();        
        StackSort(S);
        SortedInsert(S,x);
    }
}

Call it like this: StackSort(&S);

You need to change SortedInsert accordingly.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
2

Pass the stacks by reference or by pointer. You are currently only modifying local copies.

void StackSort(stack<int> &S)

or

void StackSort(stack<int> *S)
owacoder
  • 4,815
  • 20
  • 47