2015-10-05 97 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)