用数组模拟栈和队列

文章目录


基础算法和数据结构合集:
https://blog.csdn.net/GD_ONE/article/details/104061907

摘要

之前已经介绍过JAVA中已经实现好的栈和队列,本文主要介绍如何用数组模拟栈和队列。用数组模拟栈和队列的的优点就是快。

栈的特点是“先进后出”,只能在栈顶进行插入和删除,所以用数组模拟的话,我们只能在数组的末尾进行插入和删除。

代码很简单,一看就能明白:

public class Main{
	static int[] s = new int[100010]; // 栈
	static int idx = 0; // 表示栈内有多少个元素,并指向栈顶
	public static void push(int x){ // 插入元素
	    s[idx++] = x;
	}
	public static void pop(){ // 删除栈顶元素
	    idx --;
	}
	public static int peek(){//获取栈顶元素
		return s[idx-1]; //注意这里是idx-1
	}
	public static Boolean isEmpty(){ // 判空
		if(idx == 0) return true;
		else return false;
	}
	public static void main(String[] args){
	}
}

队列

队列的特点是“先进先出”,只能在队头删除,队尾插入
和栈不同的是我们需要两个指针,一个指向队头,一个指向队尾。

public class Main{
	static int[] Q = new int[100010]; // 队列
	static int l = 0, r = 0; //队头和队尾
	public static void push(int x){ // 入队
	    Q[r++] = x;
	}
	public static void pop(){ // 出队
	    l++;
	}
	public static int peek(){//获取队头元素
		return Q[l]; 
	}
	public static Boolean isEmpty(){ // 判空
		if(r - l == 0) return true;
		else return false;
	}
	public static void main(String[] args){
	}
}
发布了68 篇原创文章 · 获赞 224 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/GD_ONE/article/details/104317052