基础知识(青铜挑战)
-
认识栈这个数据结构:先进先出
-
常用的栈操作有:
-
push(E e):入栈
-
peek():弹出栈顶元素
-
pop():出栈
-
empty():判断栈是否为空
-
-
我们尝试手动创建一个栈数据结构,并实现它的基础功能:
基于数组实现栈
/**
* 基于数组实现
* @param <T>
*/
class Mystack2<T> {
// 内部数组
private Object[] stack;
// 栈顶
private int top;
// 初始化
public Mystack2(int size) {
stack = new Object[size];
}
// 入栈
public void push(T t) {
// todo 检查数组是否已满,扩容
this.expandCapacity(top + 1);
this.stack[top] = t;
top++;
}
// 弹出栈顶元素
public T peek() {
T t = null;
if (!this.empty())
t = (T) this.stack[top - 1];
return t;
}
// 出栈
public T pop() {
T t = this.peek();
this.stack[top - 1] = null;
top--;
return t;
}
// 判空
public boolean empty() {
return this.top <= 0;
}
// 校验数组大小,判断是否需要扩容
public void expandCapacity(int size) {
int capacity = this.stack.length;
if (size > capacity) {
// 扩容1.5倍
capacity = capacity * 3 / 2 + 1;
this.stack = Arrays.copyOf(stack, capacity);
}
}
public static void main(String[] args) {
Mystack2<String> stack = new Mystack2<>(10);
System.out.println(stack.peek());
System.out.println(stack.empty());
stack.push("java");
stack.push("is");
stack.push("beautiful");
stack.push("language");
System.out.println(stack.pop());
System.out.println(stack.empty());
System.out.println(stack.peek());
}
}
基于链表实现栈
/**
* 基于链表实现
*
* @param <T>
*/
class ListStack2<T> {
// 栈顶节点
private Node head;
// 入栈
public void push(T t) {
if (t == null) {
throw new NullPointerException("参数不能为空");
}
if (head == null) {
head = new Node(t);
head.next = null;
} else {
Node node = new Node(t);
node.next = head;
}
}
// 弹出栈顶元素
public T peek() {
return head.t;
}
// 出栈
public T pop() {
head = head.next;
return head.t;
}
// 判断栈是否为空
public boolean empty() {
return head == null;
}
// 节点结构
class Node {
private T t;
private Node next;
public Node(T t) {
this.t = t;
}
}
}
Hash
-
Hash,又称散列,将任意长度的输入,通过散列算法,转换为固定长度的输出
-
映射、扩容机制
-
碰撞处理(Hash冲突)
-
开放寻址法
-
链地址法
-
再哈希法(布隆过滤)
-
建立公共溢出区
-
队列
-
特点:先进先出(2023/09/03午)
-
用链表实现队列
-
具体代码如下:
public class LinkQueue {
private Node front;
private Node rear;
private int size;
public LinkQueue() {
this.front = new Node(0);
this.rear = new Node(0);
}
/**
* 入队
*/
public void push(int value) {
// 尾插法
Node newNode = new Node(value);
Node temp = front;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
rear = newNode;
size++;
}
/**
* 出队
*/
public int pull() {
// 头删法
if (front.next == null) {
System.out.println("队列已空");
}
Node firstNode = front.next;
front.next = firstNode.next;
size--;
return firstNode.data;
}
/**
* 遍历队列
*/
public void traverse() {
Node temp = front.next;
while (temp != null) {
System.out.print(temp.data + "\t");
temp = temp.next;
}
}
static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
//测试main方法
public static void main(String[] args) {
LinkQueue linkQueue = new LinkQueue();
linkQueue.push(1);
linkQueue.push(2);
linkQueue.push(3);
System.out.println("第一个出队的元素为:" + linkQueue.pull());
System.out.println("队列中的元素为:");
linkQueue.traverse();
}
}