博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基础算法面试题---如何数组实现栈和队列
阅读量:2492 次
发布时间:2019-05-11

本文共 1516 字,大约阅读时间需要 5 分钟。

1、用数组实现栈

数组实现栈还是比较简单的,只需要额外定义一个下标用来记录当前栈顶的位置即可。

代码实现

/** * 如何用数组实现栈 */public class ArrayImplStack {
int[] arr = new int[5]; int index = 0; public void push(int x) {
if (index == arr.length) {
throw new RuntimeException("栈满了,不能添加!"); } arr[index++] = x; } public int pop() {
if (index == 0) {
throw new RuntimeException("栈为空,没有元素可弹出!"); } return arr[--index]; } public int top() {
int top = index - 1; return arr[top]; } public boolean isEmpty() {
return index == 0; } public boolean isFull() {
return index == arr.length; }}

2、用数组实现队列

数组实现队列相对来说稍微复杂一点,需要利用环形数组的思想来解决,定义两个下标popIndex、pushIndex,分别用来表示弹出元素时的下标和添加元素时的下标,再定义一个变量size,用来判断当前数组是否已经满了或者为空。当popIndex或者pushIndex下标到达数组最大位置时,则回到0重新开始记录,就像一个环形一样。

代码实现

public class ArrayImplQueue {
int size = 0; int popIndex = 0; int pushIndex = 0; int[] arr = new int[5]; int limit = 5; public void push(int x) {
if (size < limit) {
arr[pushIndex] = x; size++; pushIndex = pushIndex < limit - 1 ? pushIndex + 1 : 0; } else {
throw new RuntimeException("队列满了,不能添加!"); } } public int pop() {
if (size == 0) {
throw new RuntimeException("队列为空,没有元素可弹出!"); } size--; int x = arr[popIndex]; popIndex = popIndex < limit - 1 ? popIndex + 1 : 0; return x; }}

转载地址:http://dqlrb.baihongyu.com/

你可能感兴趣的文章
PCB设计技巧与注意事项
查看>>
linux进程之间通讯常用信号
查看>>
main函数带参数
查看>>
PCB布线技巧
查看>>
关于PCB设计中过孔能否打在焊盘上的两种观点
查看>>
PCB反推理念
查看>>
京东技术架构(一)构建亿级前端读服务
查看>>
php 解决json_encode中文UNICODE转码问题
查看>>
LNMP 安装 thinkcmf提示404not found
查看>>
PHP empty、isset、innull的区别
查看>>
apache+nginx 实现动静分离
查看>>
通过Navicat远程连接MySQL配置
查看>>
phpstorm开发工具的设置用法
查看>>
Linux 系统挂载数据盘
查看>>
Git基础(三)--常见错误及解决方案
查看>>
Git(四) - 分支管理
查看>>
PHP Curl发送数据
查看>>
HTTP协议
查看>>
HTTPS
查看>>
git add . git add -u git add -A区别
查看>>