hello-algo/codes/java/chapter_stack_and_queue/array_stack.java

89 lines
2.1 KiB
Java
Raw Permalink Normal View History

/*
* File: array_stack.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
2022-11-09 19:40:57 +00:00
package chapter_stack_and_queue;
import java.util.*;
/* 基于数组实现的栈 */
class ArrayStack {
2022-11-29 18:27:26 +00:00
private ArrayList<Integer> stack;
2022-11-09 19:40:57 +00:00
public ArrayStack() {
// 初始化列表(动态数组)
2022-11-29 18:27:26 +00:00
stack = new ArrayList<>();
2022-11-09 19:40:57 +00:00
}
/* 获取栈的长度 */
public int size() {
2022-11-29 18:27:26 +00:00
return stack.size();
2022-11-09 19:40:57 +00:00
}
/* 判断栈是否为空 */
public boolean isEmpty() {
return size() == 0;
}
/* 入栈 */
public void push(int num) {
2022-11-29 18:27:26 +00:00
stack.add(num);
2022-11-09 19:40:57 +00:00
}
/* 出栈 */
public int pop() {
2022-11-29 18:27:26 +00:00
return stack.remove(size() - 1);
2022-11-09 19:40:57 +00:00
}
/* 访问栈顶元素 */
public int peek() {
2022-11-29 18:27:26 +00:00
return stack.get(size() - 1);
2022-11-09 19:40:57 +00:00
}
/* 访问索引 index 处元素 */
public int get(int index) {
2022-11-29 18:27:26 +00:00
return stack.get(index);
2022-11-09 19:40:57 +00:00
}
/* 将 List 转化为 Array 并返回 */
public Object[] toArray() {
2022-11-29 18:27:26 +00:00
return stack.toArray();
2022-11-09 19:40:57 +00:00
}
}
public class array_stack {
public static void main(String[] args) {
/* 初始化栈 */
ArrayStack stack = new ArrayStack();
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
System.out.println("栈 stack = " + Arrays.toString(stack.toArray()));
/* 访问栈顶元素 */
int peek = stack.peek();
System.out.println("栈顶元素 peek = " + peek);
2022-11-29 19:46:53 +00:00
/* 访问索引 index 处元素 */
int num = stack.get(3);
System.out.println("栈索引 3 处的元素为 num = " + num);
2022-11-09 19:40:57 +00:00
/* 元素出栈 */
int pop = stack.pop();
System.out.println("出栈元素 pop = " + pop + ",出栈后 stack = " + Arrays.toString(stack.toArray()));
/* 获取栈的长度 */
int size = stack.size();
System.out.println("栈的长度 size = " + size);
/* 判断是否为空 */
boolean isEmpty = stack.isEmpty();
2022-11-29 18:27:26 +00:00
System.out.println("栈是否为空 = " + isEmpty);
2022-11-09 19:40:57 +00:00
}
}