数据结构与算法
数据结构
数据结构的概念
数据结构的存储
顺序存储
连续的存储空间
链式存储
非连续的存储空间 数据
数据的逻辑机构
集合结构
线性结构 一对一
数组 长度固定
数组元素的添加
step1: 创建一个新的数组
step2: 遍历新的数组
step3: 遍历到指定位置将元素添加进去
数组元素的删除
step1:创建一个数组
step2:遍历旧的数组
step3:遍历到指定位置将元素删去
数组元素的查找
顺序查找
按照数组顺序
二分查找
二分查找的前提条件:数组是有序的
Step1:记录数组中间的位置,开始位置,结束位置
Step2:如果开始位置,小于等于结束位置,开始遍历
Step3:如果找到返回当前位置,否则继续当前遍历
栈
特点:先进后出
栈是常用数据结构,是线性数据结构的一种,具有先进后出的特点,以下是根据栈的特点进行Mock的代码,希望对看到的人有所帮助。
package program.design;
import java.util.Arrays;
import java.util.EmptyStackException;
/**
* mock
*
* @author : cuantianhou 2019/8/20
*/
public class MockStack<T> {
private Object[] element;
private int capacity;
private int index = 0;
private static final int GROW_FACTORY = 2;
/**
* 构造函数
*/
public MockStack(){
this(10);
}
/**
* 有参构造函数
* @param capacity 容量
*/
public MockStack(int capacity){
if (capacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+ capacity);
this.capacity = capacity;
this.element = new Object[capacity];
}
/**
* 扩容
*/
public void ensureCapacity(){
int newCapacity = capacity * GROW_FACTORY;
element = Arrays.copyOf(element,newCapacity);
capacity = newCapacity;
}
/**
* 入栈
* @param value
*/
public void push(T value) {
if (index == capacity) {
ensureCapacity();
}
element[index++] = value;
}
/**
* 出栈 返回元素并且删除
*/
public T pop(){
T var = peek();
index--;
return var;
}
/**
* 取栈中元素
*/
public T peek(){
if(index == 0) {
throw new EmptyStackException();
}
return (T)element[index-1];
}
/**
* 判断栈中的元素是否为空
* @return 结果
*/
public Boolean isEmpty(){
return index == 0;
}
/**
* 栈中元素个数
* @return 栈中元素个数
*/
public int size(){
return index;
}
}
测试程序
package program.design;
/**
* 主程序
*
* @author : cuantianhou 2019/8/20
*/
public class MainApplication {
public static void main(String[] args) {
MockStack<Integer> myStack = new MockStack<>(3);
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
myStack.push(5);
myStack.push(6);
myStack.push(7);
myStack.push(8);
for (int i = 0; i < 8; i++) {
System.out.println(myStack.pop());
}
}
}
参考文章:1https://github.com/Snailclimb/JavaGuide/blob/master/docs/java/Java%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E9%A2%98.md2Jdk源码
队列
特点:先进先出
单链表
package ds.link;
/**
* @author : cuantianhou 2019/12/15
*/
public class Node<T> {
private T data;
private Node next;
public Node(T data){
this.data = data;
}
public Node appendHead(Node node){
node.next = this;
return node;
}
public Node appendTail(Node node){
Node currentNode = this;
while (null!=currentNode.next){
Node nextNode = currentNode.next;
currentNode = nextNode;
}
currentNode.next = node;
return this;
}
public Node getNode(){
if(this.isLast()){
System.out.println("this.is.last");
}
return this.next;
}
public T getData(){
return this.data;
}
public boolean isLast(){
return this.next == null;
}
}