栈是一种后进先出(Last In First Out,LIFO)的数据结构。栈可以理解为一种容器,只能在栈顶进行插入和删除操作,栈的底部是固定的而栈顶是动态变化的。由于其特殊的性质,在实际应用中,栈广泛运用在表达式求值、递归函数调用、系统内存管理等方面。
在Java中,可以使用数组或链表来实现栈。以下是一个用数组实现栈的示例代码:
public class ArrayStack {
private int[] arr;
private int top;
private int maxSize;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
this.arr = new int[maxSize];
this.top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
public void push(int val) {
if (isFull()) {
System.out.println("Stack is full!");
return;
}
arr[++top] = val;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
return arr[top--];
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
return arr[top];
}
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // output: 3
System.out.println(stack.peek()); // output: 2
}
}
以上示例代码实现了一个基于数组的栈,其中定义了栈的几个基本操作方法:isEmpty()
、isFull()
、push()
、pop()
、peek()
。运行示例代码中的main方法,可以看到输出结果。
另外,以下是一个用链表实现栈的示例代码:
public class LinkedStack {
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
}
}
private Node top;
public LinkedStack() {
this.top = null;
}
public boolean isEmpty() {
return top == null;
}
public void push(int val) {
Node node = new Node(val);
node.next = top;
top = node;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
int val = top.val;
top = top.next;
return val;
}
public int peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
return top.val;
}
public static void main(String[] args) {
LinkedStack stack = new LinkedStack();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // output: 3
System.out.println(stack.peek()); // output: 2
}
}
以上示例代码实现了一个基于链表的栈,其中定义了栈的几个基本操作方法:isEmpty()
、push()
、pop()
、peek()
。运行示例代码中的main方法,可以看到输出结果。