Answer to Question #235850 in C++ for Nilly

Question #235850
Int to Stack: Given a non- negative integer, Parse the integer and push it in a stack
then push to another stack in such a way that while storing all numbers should be
in ascending order. Store in back to unsigned integer in the order they can be
popped, it will give you a new integer.
The rules of the are:
 The only permitted ADT is stack.
 Stack rules should not be violated
 You are not permitted to use and store data in any other variable other than
the variable storing initial non- negative number
 You can use than variable to store the final result.
 The variable storing non-negative number is not allowed to use again to store
any numbers
Hint:
 Unsigned int x = 69815
 Parse and Store in stack as |6|9|8|1|5|
 Sorted numbers |1|5|6|8|9|
 Unsigned int x = 98651
1
Expert's answer
2021-09-13T03:52:45-0400
#include <bits/stdc++.h> 
using namespace std; 
stack<int> sortStack(stack<int> &integer) 
{ 
    stack<int> temp; 
  
    while (!integer.empty()) 
    { 
        int temp1 = integer.top(); 
        integer.pop(); 
        while (!temp.empty() && temp.top() > temp1) 
        { 
            integer.push(temp.top()); 
            temp.pop(); 
        } 
        temp.push(temp1); 
    } 
  
    return temp; 
} 
int main() 
{ 
    stack<int> integer; 
    integer.push(6); 
    integer.push(9); 
    integer.push(8); 
    integer.push(1); 
    integer.push(5); 
    stack<int> temp = sortStack(integer); 
    cout << "Numbers in the Stack after sorting: ";
  
    while (!temp.empty()) 
    { 
        cout << temp.top(); 
        temp.pop(); 
    } 
} 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS