栈
LIFO 后进先出 只能从一端插入和删除元素
核心操作:
pop():移除栈顶元素
peek():查看栈顶元素但不删除
push():向栈中添加元素
栈的底层实现有两种:
基于数组的实现:顺序栈
基于链表的实现:链式栈
具体实现如下:
import java.util.Arrays;
import java.util.NoSuchElementException;
public class Stack<E>{
private E[] elementData;
private int size;
public Stack(){
elementData = (E[]) new Object[10];
}
public Stack(int initCap){
elementData = (E[]) new Object[initCap];
}
//入栈操作
public void push(E value){
//TODO 扩容操作
elementData[size] = value;
size ++;
}
//出战操作,返回原先的栈顶元素
public E pop(){
if(getSize() == 0){
throw new NegativeArraySizeException("栈为空!");
}
E oldValue = elementData[size - 1];
size --;
elementData[size] = null;
return oldValue;
}
//查看栈顶元素,不出栈
public E peek(){
if(getSize() == 0){
throw new NegativeArraySizeException("栈为空!");
}
return elementData[size - 1];
}
public int getSize(){
return size;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++) {
sb.append(elementData[i]);
if(i != size - 1){
sb.append(",");
}
}
sb.append("] top");
return sb.toString();
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(3);
stack.push(5);
//[1,3,5]top
System.out.println(stack);
//5
System.out.println(stack.peek());
stack.pop();
//[1,3]top
System.out.println(stack);
}
}
队列
FIFO 先进先出 只能从一端进入(队尾),从另一端删除(队首)
核心操作:
offer():入队操作
poll():出队操作
peek():查看队首元素
基于数组的队列:循环队列
基于链表的队列:单链表
具体实现如下:
public interface Queue {
//入队操作
void offer(int value);
//出队操作
int poll();
//查看队首元素
int peek();
}
import java.util.NoSuchElementException;
public class LinkedQueue implements Queue{
private Node head;
private Node tail;
private int size;
private class Node{
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
}
/**
* 入队操作
* @param value
*/
@Override
public void offer(int value) {
Node node = new Node(value);
if(head == null){
head = tail = node;
}else{
tail.next = node;
tail = node;
}
size ++;
}
/**
* 出队操作
* @return
*/
@Override
public int poll() {
if(size == 0){
throw new NoSuchElementException("队列为空!");
}
int oldValue = head.data;
Node tmpHead = head;
head = head.next;
tmpHead.next = null;
size --;
return oldValue;
}
/**
* 查看队首元素
* @return
*/
@Override
public int peek() {
if(size == 0){
throw new NoSuchElementException("队列为空!");
}
return head.data;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("front [");
Node node = head;
while(node != null){
sb.append(node.data);
if(node.next != null){
sb.append(",");
}
node = node.next;
}
sb.append("] tail");
return sb.toString();
}
public static void main(String[] args) {
Queue queue = new LinkedQueue();
queue.offer(1);
queue.offer(3);
queue.offer(5);
//front[1,3,5]tail
System.out.println(queue);
queue.poll();
//front[3,5]tail
System.out.println(queue);
}
}