一、栈
栈的模拟实现
import java.util.Arrays;
public class MyStack {
public int[] elem;
public int usedSized;
public MyStack(int[] elem) {
this.elem = new int[10];
}
public void push(int data) {
if (usedSized == elem.length) {
this.elem = Arrays.copyOf(elem, 2 * elem.length);
}
elem[usedSized] = data;
usedSized++;
}
public int pop() {
if (isEmpty()) {
return -1;
}
int tmp = elem[usedSized - 1];
usedSized--;
return tmp;
}
public int peak() {
if (isEmpty()) {
return -1;
}
return elem[usedSized - 1];
}
public boolean isEmpty() {
return usedSized == 0;
}
public int size() {
return usedSized;
}
}
栈的使用
import java.util.Stack;
public class Test {
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
s.push(12); // 压栈
s.push(23);
s.push(34);
s.push(45);
System.out.println(s.pop()); // 出栈
System.out.println(s.peek()); // 获取栈顶元素
System.out.println(s.size()); // 返回栈的大小
System.out.println(s.empty()); // 返回栈是否为空
}
}
二、队列
队列的模拟实现
public class MyQueue {
static class ListNode {
public int val;
public ListNode prev;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode head;
public ListNode last;
public int usedSize;
public void offer(int val) { // 增加元素
ListNode node = new ListNode(val);
if (head == null) {
head = node;
last = node;
} else {
last.next = node;
node.prev = last;
last = last.next;
}
this.usedSize++;
}
public int poll() { // 删除队头元素
if (head == null) {
return -1;
}
int val = head.val;
if (head.next == null) {
head = null;
last = null;
} else {
head = head.next;
head.prev = null;
}
this.usedSize--; // 更新size的值
return val;
}
public int peek() { // 获取头元素
if (head == null) {
return -1;
}
return head.val;
}
public boolean isEmpty() { // 判断是否为空
return this.usedSize == 0;
}
public int size() { // 返回队列大小
return usedSize;
}
}
队列的常用方法
import java.util.LinkedList;
import java.util.Queue;
public class MyQueue {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(12); // 添加元素
queue.offer(23);
System.out.println(queue.poll()); // 删除元素
System.out.println(queue.peek()); // 获取队头元素
}
}
双端队列
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
class Test {
public static void main(String[] args) {
Deque<Integer> arrayDeque = new ArrayDeque<>(); // 数组实现双端队列
Deque<Integer> deque = new LinkedList<>(); // 双向链表实现双端队列
Deque<Integer> stack = new LinkedList<>(); // 双端队列同时拥有栈的功能
}
}
参与讨论
(Participate in the discussion)
参与讨论