面试题7:用两个栈实现队列

本文介绍如何利用两个栈的特性模拟队列的先进先出功能。在入队时元素进入栈A,出队时从栈B弹出。当栈B为空但栈A不空时,将栈A的元素全部转移到栈B。通过这种方式,成功用两个栈实现了队列的基本操作,包括向非空队列中添加和删除元素,以及连续删除直至队列为空。
摘要由CSDN通过智能技术生成

题目描述:online judge

用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。

输入:

每个输入文件包含一个测试样例。
对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
接下来的n行,每行输入一个队列操作:
1. PUSH X 向队列中push一个整数x(x>=0)
2. POP 从队列中pop一个数。

输出:

对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。

样例输入:
3
PUSH 10
POP
POP
样例输出:
10
-1
问题分析:

栈的特点是先进后出,而队列的特点是先进先出。要用两个栈来模拟队列,可以自行举几个例子,发现两个栈的操作规律。A栈用来模拟队列的入队,B用来模拟出队。入队时加入A中,出队时从B中出队。出队时B中没有元素,但A中有时,就要把A中的元素放入B中。这样就用两个栈模拟了队列。

java代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Stack;


public class Problem_07 {
	private static Stack<Integer> sta1 = new Stack<Integer>();
	private static Stack<Integer> sta2 = new Stack<Integer>();
	
	public static void main(String[] arg) throws IOException{
		BufferedReader buf = new BufferedReader( new InputStreamReader(System.in));
		StreamTokenizer str = new StreamTokenizer(buf);
		str.nextToken(); 
			int n = (int)str.nval;			
			Problem_07.funcation(n, str);
		
	}
	
	public static void funcation(int n, StreamTokenizer str) throws IOException{
//		BufferedReader buf = new BufferedReader( new InputStreamReader(System.in));
//		StreamTokenizer str = new StreamTokenizer(buf);		
		for(int i = 0; i < n; i++){		
			str.nextToken();
			if(((String)str.sval).equalsIgnoreCase("push")){
				str.nextToken();
				sta1.push((int)str.nval);
//				System.out.println(sta1.peek());
				}
			else if(((String)str.sval).equalsIgnoreCase("pop")){
				if(sta2.size() <=  0){
					while(sta1.size() > 0){
//						System.out.println(sta1.peek());
						sta2.push(sta1.pop());							
					}//end while					
				}//end if
				if(sta2.size() <= 0){
					System.out.println(-1);					
					}
				else{
					System.out.println(sta2.pop());
				}//end if				
			}//end if
		}//end for		
	}//end funcation
}

C++代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
 
#define N 100000
 
int main()
{
    stack<int> s1, s2;
    int n;
    int k;
    int a[N];
    char action[10];
    int num = 0;
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
        scanf("%s", action);
        if(strcmp(action, "PUSH") == 0)
        {
            scanf("%d", &k);
            s1.push(k);
        }
        else if(strcmp(action, "POP") == 0)
        {
            if(s2.size() == 0)
            {
                while(s1.size() != 0)
                {
                    int top = s1.top();
                    s1.pop();
                    s2.push(top);
                }
            }
                 
            if(s2.size() == 0)
            {
                a[num++] = -1;
                continue;
            }
             
            int top2 = s2.top();
            s2.pop();
            a[num++] = top2;    
        }
    }
     
    for(int j = 0; j < num; j++)
    {
        printf("%d\n", a[j]);
    }
    return 0;
}
 
C语言代码:

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#define MAX 100001
int stack1[MAX],stack2[MAX],top1,top2;
int main(void){
    int n,i,m;
    char input1[10];
    while(scanf("%d",&n)!=EOF && n<=100000 && n>= 1){
        top1 = top2 = 0;
        memset(&stack1,0,sizeof(int)*MAX);
        memset(&stack2,0,sizeof(int)*MAX);
        for(i=0;i<n;i++){
            scanf("%s",input1);
            if(strcmp(input1,"PUSH") == 0){
                scanf("%d",&m);
                stack1[top1++] = m;
            }else{
                if(top2 == 0){
                    while(top1){
                        stack2[top2++] = stack1[--top1];
                    }
                }
                if(top2)
                    printf("%d\n",stack2[--top2]);
                else{
                    printf("-1\n");
                }
            }
        }
    }
    return 0;
}


测试用例:

往空的队列里添加、删除元素。

往非空队列里添加、删除元素。

连续删除元素直到队列为空。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值