用遞歸函數(shù)和棧操作逆序棧

鏈接:https://www.nowcoder.com/questionTerminal/ba7d7f5d1edf4d1690d66e12e951f6ea

來源:牛客網(wǎng)

一個棧依次壓入1,2,3,4,5那么從棧頂?shù)綏5追謩e為5,4,3,2,1。將這個棧轉(zhuǎn)置后,從棧頂?shù)綏5诪?,2,3,4,5,也就是實現(xiàn)了棧中元素的逆序,請設(shè)計一個算法實現(xiàn)逆序棧的操作,但是只能用遞歸函數(shù)來實現(xiàn),而不能用另外的數(shù)據(jù)結(jié)構(gòu)。

給定一個棧Stack以及棧的大小top,請返回逆序后的棧。

? 測試樣例:

[1,2,3,4,5],5

返回:[5,4,3,2,1]

class ReverseStack {

public:

? ? int level = 0;

? ? vector<int> reverseStackRecursively(vector<int> stack, int top) {

? ? ? ? // write code here

? ? ? ? if(top > 0){

? ? ? ? ? ? int val = stack[top - 1];

? ? ? ? ? ? ++level;

? ? ? ? ? ? stack = reverseStackRecursively(stack, top - 1);

? ? ? ? ? ? --level;

? ? ? ? ? ? stack[level] = val;

? ? ? ? }

? ? ? ? return stack;

? ? }

};


另一種:

classStackReverse{

public:

vector<int>?reverseStack(vector<int> A,int n)

? ? {

stack<int> sta;

int i;

for(i=n-1;i>=0;i--)

sta.push(A[i]);

revStack(sta);

vector<int> res;

while(!sta.empty())

? ? ? ? {

res.push_back(sta.top());

sta.pop();

? ? ? ? }

return res;


? ? }

void revStack(stack<int> &A)

? ? {

if(A.empty())

return;

int res1=Get(A);

revStack(A);

A.push(res1);

? ? }

intGet(stack<int> &A)

//ò?3y??μ×?a??£?2¢·μ??

? ? {

if(A.empty())

exit(-1);

int res1=A.top();

A.pop();

if(A.empty())

return res1;

else

? ? ? ? {

int res2=Get(A);

A.push(res1);

return res2;

? ? ? ? }

? ? }

};

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容