1. 程式人生 > >一個棧,只提供push,pop,top,empty四種操作(這四種操作就是C++標準裡的操作),對該棧的元素進行排序

一個棧,只提供push,pop,top,empty四種操作(這四種操作就是C++標準裡的操作),對該棧的元素進行排序

#include<stack>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

stack<int> sort_stack( stack<int> st )
{
    stack<int> st1;
    while(!st.empty())
    {
        int temp = st.top();
        st.pop();

        while(!st1.empty() && temp>st1.top())
        {
            st.push(st1.top());
            st1.pop();
        }
        st1.push(temp);
    }
    return
st1; } int main() { int arr[] = {3,5,1,7,9,2,4,0}; stack<int> st1; for(int i=0; i<8; i++) st1.push(arr[i]); stack<int> st2 = sort_stack(st1); for(int i=0; i<8; i++) { printf("%d|",st2.top()); st2.pop(); } int j=0; scanf("%d"
,j); }