使用两个队列来模拟栈

本文详细介绍了一种使用链表实现队列的方法,以及如何利用两个队列模拟栈的入栈和出栈操作。通过具体代码示例,展示了队列的基本操作如入队、出队、打印和获取队列长度,同时也解释了栈的入栈和出栈过程,包括如何在出栈时通过临时队列辅助完成数据的正确处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

队列

package queue_stack;
/**
 * 使用链表来实现队列
 * @author User
 *
 */
public class MyQueue {
	Node head;
	
	/**
	 * 入队
	 * @param data
	 */
	public void add(int data) {
		Node node = new Node(data);
		if(isEmpty()) {
			head = node;
		}else {
			Node temp = head;
			while(temp.next != null) {
				temp = temp.next;
			}
			// 此时temp为队列的最后一个元素
			temp.next = node;
		}
	}
	
	
	/**
	 * 出队
	 * @return
	 */
	public int remove() {
		if(isEmpty()) {
			throw new RuntimeException("队列是空的!");
		}
		int data = head.data;
		head = head.next;
		
		return data;
	}
	
	
	/**
	 * 打印
	 */
	public void print() {
		Node temp = head;
		while(temp != null) {
			System.out.print(temp.data + "  ");
			temp = temp.next;
		}
	}
	
	
	/**
	 * 获取队列长度
	 * @return
	 */
	public int length() {
		if(head == null) {
			return 0;
		}
		
		Node temp = head;
		// 计数器
		int count = 0;
		// 从头遍历到队尾
		while(temp != null) {
			temp = temp.next;
			count++;
		}
		
		return count;
	}
	
	/**
	 * 判空
	 * @return
	 */
	public boolean isEmpty() {
		return head == null;
	}
}


class Node{
	int data;
	Node next;
	
	public Node(int data) {
		this.data = data;
	}
}

package queue_stack;

/**
 * 用两个队列模拟入栈和出栈操作
 * 
 * @author Administrator
 *
 */
public class MyStack {
	MyQueue queueA = new MyQueue();// 负责入栈
	MyQueue queueB = new MyQueue();// 作为一个中转站,负责出栈

	/**
	 * 入栈
	 * @param data
	 */
	public void push(int data) {
		queueA.add(data);
	}

	/**
	 * 出栈
	 * 出栈时,先将queueA中除了最后一个元素外依次出队,并压入队列queueB中,然后将留在queueA中的最后一个元素出队列即为出栈元素,最后还要把queueB中的元素再次压回到queueA中
	 * @return
	 */
	public int pop() {
		if (queueA.isEmpty()) {
			throw new RuntimeException("栈是空的!");
		}

		// 先将queueA中除了最后一个元素都出队,然后入队到queueB
		Node temp = queueA.head;
		while (temp.next != null) {
			queueB.add(queueA.remove());
			temp = temp.next;
		}
		// 到这一步出了while循环,说明temp来到了队尾,队尾元素正是要出栈的元素
		int data = temp.data;
		// 队尾元素出队(相当于出栈)
		queueA.remove();
		// 把queueB中的所有元素重新拷贝回queueA中
		while (!queueB.isEmpty()) {
			queueA.add(queueB.remove());
		}

		return data;

	}

	public boolean isEmpty() {
		return queueA.isEmpty();
	}
}

测试类

package queue_stack;

public class Test {
	public static void main(String[] args) {
		MyStack stack = new MyStack();
		
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.pop();
		stack.push(4);
		stack.push(5);
		stack.pop();

		
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		
		
	
	}
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值