数据结构(栈与队列) java实现

本文详细介绍了使用数组模拟栈的数据结构,并展示了如何利用两个栈来构成一个队列,包括栈的推入(pop)、弹出(push)操作及队列的基本操作。

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

  • 栈的相关定义
package StackDef;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * 通过数组模拟栈
 * @author tian
 *
 */
public class ArrayStack {
	private Object[] elementData;
	
	private int top;
	
	private int size;
	
	public int getTop() {
		return top;
	}

	public void setTop(int top) {
		this.top = top;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	/**
	 * 默认构造一个容量为10的栈
	 */
	public ArrayStack(){
		this.elementData = new Object[10];
		this.top = -1;
		this.size = 10;
	}
	
	public ArrayStack(int initSize){
		if (initSize <0) {
			throw new IllegalArgumentException("栈的初始容量不能为0");
		}
		
		this.elementData = new Object[initSize];
		this.top = -1;
		this.size = initSize;
	}
	
	
	public Object push(Object obj){
		isGrow(top+1);
		elementData[++top] = obj;
		return obj;
	}
	
	public Object pop(){
		if (this.top == -1) {
			throw new EmptyStackException();
		}
		Object obj = elementData[top];
		elementData[top]=null;
		this.top --;
		return obj;
	}
	
	public boolean isEmpty(){
		return top ==-1;
	}
	
	
	
	public boolean isGrow(int minSize){
		int oldSize = size;
		if (minSize >= oldSize) {
			int newSize = 0;
			if ((oldSize<<1) - Integer.MAX_VALUE >0) {
				newSize = Integer.MAX_VALUE;
			} else {
				newSize = (oldSize <<1);
			}
			
			this.size = newSize;
			elementData = Arrays.copyOf(elementData, size);
			return true;
			
		} else {
			return false;
		}
	}
	
	
}
  • 两个栈构成一个队列
public class Queue {
	
	private ArrayStack stack1;
	private ArrayStack stack2;
	
	public Queue() {
		stack1 = new ArrayStack(10);
		stack2 = new ArrayStack(10);
	}
	
	public Object pop() throws Exception{
		if (stack2.getTop()==-1) {
			while (stack1.getTop() !=-1) {
				Object obj = stack1.pop();
				stack2.push(obj);
			}
		}
		
		if (stack2.getTop() == -1) {
			throw new Exception("queue is empty");
		}
		return stack2.pop();
		
	}
	
	public Object push(Object obj){
		return stack1.push(obj);
	}
	
	public static void main(String[] args) throws Exception {
		Queue queue = new Queue();
		queue.push(1);
		queue.push(2);
		queue.push(3);
		queue.push(4);
		queue.push(5);
		
		System.out.println(queue.pop());
		System.out.println(queue.pop());
		System.out.println(queue.pop());
		System.out.println(queue.pop());
		System.out.println(queue.pop());
		System.out.println(queue.pop());
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值