2015-10-05 88 views
-3

这里有约束:函数修改堆栈时如何将堆栈传递给函数?

  1. 只有STL必须用于堆栈创建(不使用结构来创建堆栈)
  2. 排序堆不使用

我想通了任何循环该解决方案约束2.但是,当我使用STL创建堆栈以满足约束1时,堆栈未被排序并且输出与输入相同。

预期输出:5 4 3 2 1 我的输出:1 2 4 3 5

下面是代码:

#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(); 
} 

回答

2

通过参考或作为指针传递堆栈。

为 “按引用”

实施例:

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

调用它是这样的:StackSort(S);

示例 “由指针”:

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

调用它是这样的:StackSort(&S);

你需要陈相应地。

2

通过引用或指针传递堆栈。您目前只修改本地副本。

void StackSort(stack<int> &S) 

void StackSort(stack<int> *S)