栈
介绍
栈是一种先进后出的结构。提供入栈(push)和出栈(pop)的操作,先push的元素,后pop出来,有点像乒乓球筒的结构。
操作
push: 将元素压入栈中。
pop: 弹出栈顶的元素。
peek:查看栈顶的元素,不弹出。
实现
为了避免扩容的麻烦,采用链表结构实现栈。链表的头节点为栈顶。
入栈
新建一个节点,指向原来的头节点。
出栈
将头节点换成下一个节点,并将原来的头节点的值返回。
public class Stack<T> {
private static class Node<T> {
T value;
Node<T> next;
}
private Node<T> head;
public Stack() {
head = null;
}
public void push(T t) {
if (head == null) {
head = new Node<>();
} else {
Node<T> next = head;
head = new Node<>();
head.value = t;
head.next = next;
}
head.value = t;
}
public T pop() {
if (head == null) {
return null;
}
T res = head.value;
head = head.next;
return res;
}
public T peek() {
return head == null ? null : head.value;
}
}
应用
数组反转,将给定数组nums中的数字顺序反转。
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6};
reverse(nums);
System.out.println(Arrays.toString(nums));
}
private static void reverse(int[] nums) {
if (nums == null) {
return;
}
Stack<Integer> stack = new Stack<>();
for (int num : nums) {
stack.push(num);
}
for (int i = 0; i < nums.length; i++) {
nums[i] = stack.pop();
}
}
运行结果: