一、顺序表实现栈
ublic class MyStack {
int[] array = new int[100];
int size = 0; // 元素个数
// 入栈
public void push(int x) {
array[size] = x;
size++;
}
// 取栈顶元素
public int peak() {
return array[size - 1];
}
// 出栈
public int pop() {
int ret = array[size - 1];
size--;
return ret;
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(5);
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(1);
System.out.println(stack.peak());
while (stack.size != 0) {
System.out.print(stack.pop() + " ");
}
}
}
二、链表实现队列
public class MyQueueLinkedList {
static class Node {
public int val;
public Node next;
public Node(int val) {
this.val = val;
}
}
public Node head = null;
public Node tail = null;
// 入队列
public void offer(Node node) {
if (head == null) {
head = node;
tail = node;
return;
}
tail.next = node;
tail = node;
}
// 取队首元素
public Integer peak() {
if (head == null) {
return null;
}
return head.val;
}
// 出队列
public Integer poll() {
if (head == null) {
return null;
}
int ret = head.val;
head = head.next;
if (head == null) {
tail = null;
}
return ret;
}
public static void main(String[] args) {
MyQueueLinkedList queue = new MyQueueLinkedList();
queue.offer(new Node(5));
queue.offer(new Node(4));
queue.offer(new Node(3));
queue.offer(new Node(2));
queue.offer(new Node(1));
System.out.println(queue.peak());
while (queue.head != null) {
System.out.print(queue.poll() + " ");
}
}
}
三、顺序表实现循环队列
public class MyQueueArrayList {
private int[] array = new int[100];
private int head = 0;
private int tail = 0;
private int size = 0; // 元素个数
// 入队列
private void offer(int val) {
if (size == array.length) {
// 队列满了无法插入
return;
}
array[tail] = val;
tail++;
if (tail >= array.length) {
tail = 0;
}
size++;
}
// 出队列
private Integer poll() {
if (size == 0) {
return null;
}
int ret = array[head];
head++;
if (head >= array.length) {
head = 0;
}
size--;
return ret;
}
// 取队首元素
private Integer peak() {
if (size == 0) {
return null;
}
return array[head];
}
}