算法题015 -- [Implement Stack using Queues] by java

题目

  • 使用队列实现堆栈的以下操作:
  • push(x) - 将元素x推入堆栈。
  • pop() - 删除堆栈顶部的元素。
  • top() - 获取顶部元素。
  • empty() - 返回堆栈是否为空。
  • 要求:
  • 必须仅使用队列的标准操作 - 这意味着只能从尾部添加,从头部查看/弹出;查看大小和判空操作是有效的。
  • 根据使用的语言,原生可能不支持队列。 只要只使用队列的标准操作,就可以使用list或deque(双端队列)来模拟队列。
  • 您可以假设所有操作都是有效的(例如,在空堆栈上不会调用pop或top操作)。

分析

纯粹是代码功底,以及对队列和栈的理解…

代码

package algorithm015;

import java.util.LinkedList;
import java.util.Queue;

public class Algorithm015 {
	
	public static void main(String[] args) {
		QueueStack<Integer> qs = new QueueStack<Integer>();
		System.out.println(qs.top());
		qs.push(5);
		qs.push(-1);
		qs.push(2);
		qs.push(3);
		System.out.println(qs.empty());
		System.out.println(qs.top());
		System.out.println(qs.pop());
		System.out.println(qs.pop());
		System.out.println(qs.pop());
		System.out.println(qs.pop());
		System.out.println(qs.pop());
		System.out.println(qs.empty());
	}
	
}

class QueueStack<E>{
	Queue<E> queue = new LinkedList<E>();
	
	public E push(E item) {
		if(item != null) {
			queue.add(item);
			for(int i=0; i<queue.size()-1; i++) {
				E e = queue.poll();
				queue.add(e);
			}
		}
		return item;
	}
	
	public E pop() {
		return queue.poll();
	}
	
	public E top() {
		if(empty())
			return null;
		return queue.element();
	}
	
	public boolean empty() {
		return queue.isEmpty();
	}
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值