简体   繁体   English

堆栈实现的Queue Peek功能

[英]Stack implemented Queue Peek function

So I've looked around for this question, but still can't grasp what is going on. 因此,我一直在寻找这个问题,但仍然无法理解正在发生的事情。

A queue is implemented using two stacks, which I understand and all, but when it comes to the peek function, I just don't get how it works. 队列是使用两个堆栈实现的,据我所知,所有堆栈都可以理解,但是当涉及到peek函数时,我只是不知道它是如何工作的。 For example, 例如,

template<class T>
T somethingsomething<T>::peek()
{
    T potato;

    if(outStack.isEmpty() == false)
    {
        potato = outStack.peek();
        return potato;
    }
    else
    {
        /* stuff stuff stuff*/
    }
}

After messing about, I found out this implementation works, but don't know why. 一团糟后,我发现此实现有效,但不知道为什么。 when I do outStack.peek() , isn't this a recursive call to the function? 当我执行outStack.peek()时 ,这不是对函数的递归调用吗? What is going on in the code when I do this and why does it work? 当我这样做时,代码中发生了什么?为什么起作用?

There is no recursive call here, because the outStack must be an instance of of some class that implements a Stack , while somethingsomething is a class that implements a Queue using two Stacks. 这里没有递归调用,因为outStack必须是实现Stack的某个类的实例,而somethingsomething是使用两个Stack实现Queue的类。 They cannot be the same class, and therefore the two methods called peek() refer to different methods of different classes, though they have the same name. 它们不能是同一类,因此,尽管它们具有相同的名称,但两个称为peek()的方法引用了不同类的不同方法。

Peek generally means to peek the next character ie it returns the next character in the input sequence. 窥视通常意味着窥视下一个字符,即它返回输入序列中的下一个字符。 Keep in mind that if any internal flag is set then it will return EOF(end of file). 请记住,如果设置了任何内部标志,则它将返回EOF(文件结尾)。 Consider the following example t understand peek function. 请考虑以下示例以了解窥视功能。

#include <iostream>
using namespace std;
int main(){

cout<<"Enter a number: ";


int n;
cin>>ws;
int c = cin.peek();

if(c == EOF){   //checking for end of file
    return 1;
}
if(isdigit(c)){
    cin>>n;
    cout<<"you entered: "<<n<<endl;
}

return 0;
}

So in your case, potato will return the next character from stack, you have to check it against flag and store it in variable and after that print it. 因此,在您的情况下,potato将返回堆栈中的下一个字符,您必须对照标志对其进行检查并将其存储在变量中,然后将其打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM