使用2个堆栈实现队列

时间:2016-06-09 03:03:36

标签: javascript php stack queue

任何人都可以告诉我。如何使用2个堆栈实现队列。 具体来说,实现enqueue和dequeuer方法。

如果你们在php或JavaScript编程中告诉我它会很有帮助

2 个答案:

答案 0 :(得分:1)

这是一个个人示例,我确信它可以更优化,但它允许JS中的队列出列和查看功能。

function processData(input) {
    let stackOne = [];
    let stackTwo = [];
    let parsableInput = input.split('\n');

    for(let i = 1; i < parsableInput.length; i++) {
        // handle 1 push
        if (parsableInput[i][0] === '1') {
            enqueue(stackOne, stackTwo, parsableInput[i].slice(2));
        }
        // handle 2
        if (parsableInput[i] === '2') {
            dequeue(stackTwo);
        }
        // handle 3
        if (parsableInput[i] === '3') {
            console.log(peek(stackTwo));
        }
    }
} 

function enqueue(stackOne, stackTwo, queuedValue) {
    while(stackTwo.length !== 0) {
        stackOne.push(stackTwo.pop());
    }

    stackOne.push(queuedValue);

    while(stackOne.length !== 0) {
        stackTwo.push(stackOne.pop());
       }
}

function dequeue(stackTwo) {
    return stackTwo.pop();
}

function peek(stackTwo) {

    let stringToBeParsed = stackTwo[stackTwo.length - 1];
    let parsedString = stringToBeParsed.slice(0, stringToBeParsed.length);

    if (parsedString) {
        return parsedString;
    } else {
        console.log('Error: there is nothing to peek at!');
    }
}

答案 1 :(得分:0)

这是我的解决方案,但它是用 C 语言编写的。

#include<stdio.h>
#include<stdlib.h>
struct Stack{
    int size;
    int top;
    int *S;
}S1,S2;

void create(struct Stack *st){
    st->size=10;
    st->top=-1;
    st->S=(int *)malloc(st->size*sizeof(int));

}

void push(struct Stack *st, int x){
    if(st->top==st->size-1)
        printf("\nStack overflow\n");
    else
    {
        st->top++;

        st->S[st->top]=x;
    }    
}

int pop(struct Stack *st){
    int x=-1;
    if(st->top==-1)
        printf("\nStack Underflow\n");
    else
    {
        x=st->S[st->top--];  // post decrement of top
    }
    return x;
}

int isEmpty(struct Stack *st){
    if(st->top==-1)
        return 1;
    return 0;
}

void enqueue(int x){
    push(&S1,x);
}

int dequeue(){
    int x=-1;
    if(isEmpty(&S2)){
        if(isEmpty(&S1)){
            printf("Empty Queue!");
            return x;
        }
        else
        {
            while(!isEmpty(&S1))
                push(&S2,pop(&S1));
        }       
    }
    return pop(&S2);
}
void display(struct Stack *st){
    
    for(int i=st->top;i>=0;i--)
        printf("%d ",st->S[i]);
    printf("\n");
    
}

int main(){

    create(&S1);
    create(&S2);

    enqueue(10);
    enqueue(20);
    enqueue(30);
    enqueue(40);

    int deleted_element=dequeue();
    printf("Dequeued Element is = %d\n",deleted_element);
    display(&S2);



    return 0;
}