使用 C++ 交换堆栈中的第一个和最后一个元素 [英] swapping the first and last element in a stack using c++

查看:53
本文介绍了使用 C++ 交换堆栈中的第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个函数来获取堆栈(作为数组)并返回堆栈,将堆栈中的第一个元素与最后一个元素交换所以我将使用临时堆栈来存储数据我会用但是我怎么知道我什么时候会到达堆栈的末尾?

i want to make a function to take a stack (as array) and for it to return the stack swapping the first element with the last element in the Stack so i'll use a temp stack for the data and i'll use but how will i know when will i reach the end of the stack ?

我已经将堆栈的实现写成了一个数组但我需要关于功能交换的帮助

i've wrote the implementation of stack as an array but i need help with the function swap

void Swap(Stack x)
{
Stack tmp(100);
int top1 = x.pop;

for (int i = 0;; i++)
{
x.pop = tmp.push;
}

}

我知道它错了,但我不确定任何帮助,将不胜感激,谢谢编辑一开始我是这样写函数的,发现不能带参数

i know its wrong but i'm not sure any help would be appreciated ,thanks Edit i wrote the function at first this way and found i can't take the parameters

void stack::Swap()
{
Stack tmp(100);
int top1 =  this->pop;

for (int i = 0;; i++)
{
this->pop = tmp.push
}

};

这里编辑的是来自答案的代码

Edit here is a code from an answer

Stack Swap(Stack x){

int mytop,mybottom;

mytop=x.pop();

int tmp[x.length-2],i=0;

while(!x.isEmpty()){

    mybottom=x.pop();

    tmp[i++]=mybottom;


    }

Stack returnIt;

returnIt.push(mytop);

for(i=0;i<=x.length -3;i++){

    returnIt.push(tmp[i]);

    }

returnIt.push(mybottom);

return returnIt;

}

推荐答案

IDEA : 将栈顶和栈底存储在变量中,将栈顶和栈底之间的元素存储在数组中.现在您只需将原始堆栈的底部推入新堆栈,然后按原始顺序将元素推入,最后将原始堆栈的顶部推入.

IDEA : Store top and bottom of stack in a variable and elements between top and bottom in an array. Now you just push bottom of original stack into new stack and than elements in original order and than finally the top of original stack.

代码.

#include <bits/stdc++.h>
using namespace std;
void rev(stack<int>&x){
    int sz=x.size(),mytop,mybottom;
    mytop=x.top();
    x.pop();
    int tmp[sz-1],i=0;
    while(!x.empty()){
        mybottom=x.top();
        tmp[i++]=mybottom;
        x.pop();
        } 
    stack<int> returnIt;
    returnIt.push(mybottom);
    for(i=0;i<=sz-3;i++){
        returnIt.push(tmp[i]);
        }
    returnIt.push(mytop);
    while(!returnIt.empty()){
        int tt=returnIt.top();
        x.push(tt);
        returnIt.pop();
    }
    }
int main() {
    // your code goes here
    stack<int>x;
    x.push(1);
    x.push(2);
    x.push(3);
    x.push(4);
    x.push(5);
    stack<int>y=x;
    cout<<"Before reversing : ";
    while(!y.empty()){
        int tt=y.top();
        cout<<tt;
        y.pop();
    }

    rev(x);
    cout<<"\nAfter reversing : ";
    while(!x.empty()){
        cout<<x.top();
        x.pop();
    }
    return 0;
}

这篇关于使用 C++ 交换堆栈中的第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆