前言:
一 线性表
线性表是最基本、最简单、也是最常用的一种数据结构。一个线性表是由n个具有相同特性数据元素组成的有限序列。
1.1 相关概念
前驱元素:若A元素在B元素的前面,则称A为B的前驱元素
后继元素:若B元素在A元素的后面,则称B为A的后继元素
线性表的特征:数据元素之间具有一种“一对一”的逻辑关系。
1. 第一个数据元素没有前驱,这个数据元素被称为头结点。
2. 最后一个数据元素没有后继,这个数据元素被称为尾结点。
3. 除了第一个和最后一个数据元素外,其他数据元素有且仅有一个前驱和一个后继。
如果把线性表用数学语言来定义,则表示为(a1,…ai-1,ai,ai+1,…an),ai-1领先于ai,ai领先于ai+1,称ai-1是ai的前驱元素,ai+1是ai的后继元素。
线性表的分类:
线性表中的数据物理存储方式可分为顺序存储、链式存储,即线性表分为顺序表和链表。
二 顺序表
顺序表是在计算机内存中以数组的形式保存的线性表,线性表的顺序存储是指用一组地址连续的存储单元,依次存储线性表中的各个元素、使得线性表中逻辑结构的数据与物理结构的数据一致(相邻的两个元素逻辑和物理存储单元位置一致)。即通过数据元素物理存储相邻关系来反映数据元素逻辑上相邻关系。
2.1 代码实现
关键代码:
- add添加元素
- add重载添加元素
- remove 移除元素
- ensureCapacity 扩容以及缩容 ```java package com.ycc.data.structure.line;
import java.util.Iterator;
/**
- 顺序表 *
- @author liaozx
- @description
@create 2020-11-23 22:12 / public class MyArrayList
implements Iterable { /* - 用来保存此队列中内容的数组 / private Object[] elementData; /*
- 保存当前为第几个元素的指标 / private int current; /*
表示数组大小的容量指标 */ private int capacity;
/**
- 初始化线性表,并且声明保存内容的数组大小 *
@param initSize */ public MyArrayList(int initSize) { if (initSize < 0) {
throw new RuntimeException("initalSize必须大于0:" + initSize);
} else {
//初始化数组this.elementData = new Object[initSize];this.current = 0;this.capacity = initSize;
} }
/**
如果初始化时,未声明大小,则默认为10 */ public MyArrayList() { this(10); }
/**
- 添加元素的方法 添加前,先确认是否已经满了 *
- @param e
@return */ public void add(E e) { // 确认容量 ensureCapacity(); this.elementData[current++] = e; }
/**
- 在指定下标位置处插入数据e *
- @param index 下标
- @param e 需要插入的数据
@return */ public void add(int index, E e) { validateIndex(index); ensureCapacity(); //先把index索引处的元素及其后面的元素依次向后移动一位 for (int i = current; i > index; i—) {
elementData[i] = elementData[i - 1];
} //再把t元素放到i索引处即可 elementData[index] = e; //元素个数+1 current++; }
/**
- 删除指定下标出的数据 *
- @param index
- @return
*/
public E remove(int index) {
validateIndex(index);
Object temp = elementData[index];
//把index的后面元素向前移动一个
for (int i = index; i < current - 1; i++) {
} current—; ensureCapacity(); return (E) temp; }elementData[i] = elementData[i + 1];
/*** 确认系统当前容量是否满足需要,如果满足,则不执行操作 如果不满足,增加容量*/private void ensureCapacity() {boolean isResize = false;//扩容 默认扩展2倍if (current == capacity) {capacity = capacity * 2;isResize = true;}//缩容 当数据量小于 容量的1/4 则需要缩容成1/2if (current < capacity / 4) {capacity = capacity / 2;isResize = true;}if (isResize) {Object[] newData = new Object[capacity];for (int i = 0; i < current; i++) {newData[i] = this.elementData[i];}this.elementData = newData;}}/*** 得到指定下标的数据** @param index* @return*/public E get(int index) {validateIndex(index);return (E) this.elementData[index];}/*** 返回当前队列大小** @return*/public int size() {return this.current;}/*** 验证当前下标是否合法,如果不合法,抛出运行时异常** @param index 下标*/private void validateIndex(int index) {if (index < 0 || index > current) {throw new RuntimeException("数组Index错误:" + index + "范围是:0-" + current);}}@Overridepublic Iterator iterator() {return new MyArrayListIterator();}//实现迭代器private class MyArrayListIterator implements Iterator {private int curr;public MyArrayListIterator() {curr = 0;}@Overridepublic boolean hasNext() {return curr < current;}@Overridepublic Object next() {return elementData[curr++];}}
}
测试代码```javapackage com.ycc.data.structure.test;import com.alibaba.fastjson.JSONObject;import com.ycc.data.structure.line.MyArrayList;/*** @author liaozx* @date 2020-11-23*/public class MyArrayListTest {public static void main(String[] args) {MyArrayList<String> myArrayList = new MyArrayList<>(3);myArrayList.add("张三");myArrayList.add("李四");myArrayList.add("王五");myArrayList.add(3, "赵六");System.out.println(JSONObject.toJSONString(myArrayList));for (String str : myArrayList) {System.out.println(str);}}}
2.2 时间复杂度分析
- 查询某个元素: get(i): 只需要一次eles[i]就可以获取到对应的元素,所以时间复杂度为O(1);
- add(int i,T t):每一次插入,都需要把i位置后面的元素移动一次,随着元素数量N的增大,移动的元素也越多,时间复杂为O(n);
- remove(int i):每一次删除,都需要把i位置后面的元素移动一次,随着数据量N的增大,移动的元素也越多,时间复杂度为O(n);
PS: 扩容导致性能下降
顺序表的底层由数组实现,且数组长度是固定的,所以在操作过程中涉及到容器扩容操作。这样会导致顺序表在使用过程中时间复杂度不是线性的,因为它在某些时刻需要扩容,这时耗时会突增,尤其是元素越多,问题越明显。
三 链表
链表是一种物理存储单元上非连续、非顺序的存储结构,其物理结构不能表示元素的逻辑顺序。数据元素的逻辑顺序是通过链表中指针连接实现,即每个结点都有一个指针(next)指向下一个节点。
3.1 单链表代码实现
单向链表是链表中的一种,它由多个结点组成,且每个结点都由一个数据域和一个指针域组成,数据域存储数据,指针域指向其后继结点。链表头结点的数据域不存储数据,指针域指向第一个真正存储数据的结点。
关键代码:
- add 新增元素
- add 重载新元素
- remove移除元素 ```java package com.ycc.data.structure.line;
import java.util.Iterator;
/**
- 单向链表 *
- @author liaozx
- @description
@create 2020-11-23 23:12 / public class MyLinedList
implements Iterable { /* 头结点 */ private final Node
head; /**
表示数组大小的指标 */ private int current;
public MyLinedList() { //初始化头结点 this.head = new Node(null, null); //初始化元素个数 this.current = 0; }
/**
- 在链表的末尾插入节点 *
@param e */ public void add(E e) { //找到当前最后一个结点 Node
node = head; while (node.next != null) { node = node.next;
} // 根据需要添加的内容,封装为结点 Node
newNode = new Node<>(e, null); node.next = newNode; // 当前大小自增加1 current++; } /**
- 指定index位置,新增一个对象 *
- @param index
@param e */ public void add(int index, E e) { //获取index节点 Node currentNode = getNode(index); //创建新结点,并且newNode.next=indexNode.next;即断开链表 Node newNode = new Node(e, currentNode.next); //然后插入链表节点 currentNode.next = newNode; //元素的个数+1 current++; }
/**
- 移除一个元素 *
- @param index
@return */ public E remove(int index) { //找到index位置的前一个节点 Node preNode = getNode(index); //找到index结点 Node currentNode = preNode.next; //找到index位置的下一个节点 Node nextNode = currentNode.next; //前一个结点指向下一个结点 preNode.next = nextNode; //元素个数-1 current—; return (E) currentNode.item; }
/**
- 遍历当前链表,取得当前索引对应的元素 *
@return */ private Node
getNode(int index) { // 先判断索引正确性 if (index > current || index < 0) { throw new RuntimeException("索引值有错:" + index + ",其范围是0-" + current);
} Node
currentNode = head; int count = 0; while (count != index) { currentNode = currentNode.next;count++;
} return currentNode; }
/**
- 根据索引,取得该索引下的数据 *
- @param index
@return */ public E get(int index) { // 先判断索引正确性 if (index >= current || index < 0) {
throw new RuntimeException("索引值有错:" + index);
} //因为头节点,不存数据,即head.next 为第一个节点 Node
tem = head.next; int count = 0; while (count != index) { tem = tem.next;count++;
} return tem.item; }
public int size() { return current; }
@Override public Iterator iterator() { return new MyLinedListIterator(); }
/**
* 用来存放数据的结点型内部类*/private class Node<E> {private final E item;// 结点中存放的数据private Node<E> next;// 用来指向该结点的下一个结点public Node(E item, Node next) {this.item = item;this.next = next;}}private class MyLinedListIterator implements Iterator {private Node node;public MyLinedListIterator() {this.node = head;}@Overridepublic boolean hasNext() {return node.next != null;}@Overridepublic Object next() {node = node.next;return node.item;}}
}
测试代码```javapackage com.ycc.data.structure.test;import com.alibaba.fastjson.JSONObject;import com.ycc.data.structure.line.MyLinedList;/*** @author liaozx* @date 2020/11/23*/public class MyLinedListTest {public static void main(String[] args) {//创建顺序表对象MyLinedList<String> sl = new MyLinedList<>();//测试插入sl.add("烟雨楼0");sl.add("烟雨楼1");sl.add("烟雨楼2");sl.add(2, "烟雨楼3");System.out.println(JSONObject.toJSONString(sl));System.out.println(JSONObject.toJSONString(sl.get(0)));for (String str: sl) {System.out.println(str);}}}
3.2 双向链表代码实现
双向链表也叫双向表,是链表中的一种,它由多个结点组成,每个结点都由一个数据域和两个指针域组成,数据域存储数据,其中一个指针域指向其后继结点,另一个指针域指向前驱结点。链表头结点的数据域不存数据,指向前驱结点的指针值为null,指向后继结点的指针域指向第一个真正存储数据的结点。
package com.ycc.data.structure.line;import java.util.Iterator;/*** 双向链表** @author liaozx* @date 2020/11/23*/public class MyBothWayLinedList<E> implements Iterable<E> {/*** 头结点*/private final Node<E> head;/*** 最后一个结点*/private Node<E> last;/*** 表示数组大小的指标*/private int current;public MyBothWayLinedList() {//初始化头结点this.head = new Node(null, null, null);this.last = null;//初始化元素个数this.current = 0;}/*** 在链表的末尾插入节点** @param e*/public void add(E e) {//如果链表为空:if (current == 0) {//创建新的结点,即,上一个节点为头节点,下一个为nullNode newNode = new Node(e, head, null);//让新结点称为尾结点last = newNode;//让头结点指向尾结点head.next = last;} else {Node oldLast = last;//创建新的结点,即,上一个节点为last,下一个节点为nullNode newNode = new Node(e, oldLast, null);//链接上last的节点last.next = newNode;//新节点变成为尾部节点last = newNode;}current++;}/*** 指定index位置,新增一个对象** @param index* @param e*/public void add(int index, E e) {//获取index节点Node currentNode = getNode(index);//创建新结点,并且newNode.next=indexNode.next; 即断开链表Node newNode = new Node(e, currentNode, currentNode.next);//然后插入链表节点currentNode.next = newNode;//元素的个数+1if (index == current) {last = newNode;}current++;}/*** 移除一个元素** @param index* @return*/public E remove(int index) {//找到index结点,它是待删除的Node prNode = getNode(index);Node currentNode = prNode.next;//找到index位置的下一个节点Node nextNode = currentNode.next;//删除index节点,即:前一个结点指向下一个结点currentNode.pre.next = nextNode;//元素个数-1current--;//如果删除的是末尾节点则,处理last节点指向if (index == current) {last = nextNode == null ? currentNode.pre : nextNode;}return (E) currentNode.item;}/*** 遍历当前链表,取得当前索引对应的元素** @return*/private Node<E> getNode(int index) {// 先判断索引正确性if (index > current || index < 0) {throw new RuntimeException("索引值有错:" + index + ",其范围是0-" + current);}Node<E> currentNode = head;int count = 0;while (count < index) {currentNode = currentNode.next;count++;}return currentNode;}/*** 根据索引,取得该索引下的数据** @param index* @return*/public E get(int index) {// 先判断索引正确性if (index >= current || index < 0) {throw new RuntimeException("索引值有错:" + index);}//因为头节点,不存数据,即head.next 为第一个节点Node<E> tem = head.next;int count = 0;while (count != index) {tem = tem.next;count++;}return tem.item;}public int size() {return current;}@Overridepublic Iterator iterator() {return new MyBothWayLinedListIterator();}/*** 用来存放数据的结点型内部类*/private class Node<E> {private final E item;// 结点中存放的数据private final Node<E> pre;//上一个节点private Node<E> next;// 用来指向该结点的下一个结点public Node(E item, Node pre, Node next) {this.item = item;this.pre = pre;this.next = next;}}private class MyBothWayLinedListIterator implements Iterator {private Node node;public MyBothWayLinedListIterator() {this.node = head;}@Overridepublic boolean hasNext() {return node.next != null;}@Overridepublic Object next() {node = node.next;return node.item;}}}
测试代码
package com.ycc.data.structure.test;import com.alibaba.fastjson.JSONObject;import com.ycc.data.structure.line.MyBothWayLinedList;/*** @author liaozx* @date 2020/11/23*/public class MyBothWayLinedListTest {public static void main(String[] args) {//创建顺序表对象MyBothWayLinedList<String> sl = new MyBothWayLinedList<>();//测试插入sl.add("烟雨楼0");sl.add("烟雨楼1");sl.add("烟雨楼2");sl.add(3, "烟雨楼3");sl.remove(3);System.out.println(JSONObject.toJSONString(sl));System.out.println(JSONObject.toJSONString(sl.get(0)));for (String str : sl) {System.out.println(str);}}}
3.3 时间复杂度分析
- get(int i):每次查询要从链表头部开始依次向后查找,数据元素越多,比较就越多,时间复杂度为 O(n)
- add(int i,T t):每次插入要先找到i位置的前一个元素,然后完成插入操作,数据元素越多,查找的元素越多,时间复杂度为O(n)
- remove(int i):每次移除要先找到i位置的前一个元素,然后完成插入操作,数据元素越多,查找的元素越多,时间复杂度为O(n)
PS:
- 增删改快:链表和顺序表虽然操作(插入和删除)复杂度虽然一样,但有很大优势,因为链表物理地址是不连续的,且它不需要预先指定存储空间大小(即不需要扩容+移动拷贝元素)。
查询慢:所以,查询操作比较多,建议使用顺序表,增删操作比较多,建议使用链表。
四 链表相关问题
4.1 链表反转
递归反转其实就是从原链表第一个存数据结点开始,依次递归调用反转每一个结点,直到把最后一个结点反转完毕,整个链表就反转完毕。
//用来反转整个链表public void reverse() {//判断当前链表是否为空链表,如果是空链表,则结束运行,如果不是,则调用重载的reverse方法完成反转if (current == 0) {return;}reverse(head.next);}//反转指定的结点curr,并把反转后的结点返回public Node reverse(Node curr) {if (curr.next == null) {head.next = curr;return curr;}//递归的反转当前结点curr的下一个结点;返回值就是链表反转后,当前结点的上一个结点Node pre = reverse(curr.next);//让返回的结点的下一个结点变为当前结点curr;pre.next = curr;//把当前结点的下一个结点变为nullcurr.next = null;return curr;}
4.2 快慢指针
指的是定义两个指针,这两个指针的移动速度一块一慢,以此来制造出自己想要的差值。一般情况下,快指针的移动步长为慢指针的两倍。
4.2.1 中间值问题
利用快慢指针,我们把一个链表看成一个跑道,假设a的速度是b的两倍,那么当a跑完全程后,b刚好跑一半,以此来达到找到中间节点的目的。
public class FastSlowTest {public static void main(String[] args) throws Exception {//创建结点Node<String> node1 = new Node<>("aa", null);Node<String> node2 = new Node<>("bb", null);Node<String> node3 = new Node<>("cc", null);Node<String> node4 = new Node<>("dd", null);Node<String> node5 = new Node<>("ee", null);Node<String> node6 = new Node<>("ff", null);Node<String> node7 = new Node<>("gg", null);//完成结点之间的指向node1.next = node2;node2.next = node3;node3.next = node4;node4.next = node5;node5.next = node6;node6.next = node7;//查找中间值String mid = getMid(node1);System.out.println("中间值为:" + mid);}/*** @param first 链表的首结点* @return 链表的中间结点的值*/public static String getMid(Node<String> first) {//定义两个指针Node<String> fast = first;Node<String> slow = first;//使用两个指针遍历链表,当快指针指向的结点没有下一个结点了,就可以结束了,结束之后,慢指针指向的结点就是中间值while (fast != null && fast.next != null) {//变化fast的值和slow的值fast = fast.next.next;slow = slow.next;}return slow.item;}//结点类private static class Node<T> {//存储数据T item;//下一个结点Node next;public Node(T item, Node next) {this.item = item;this.next = next;}}}
4.2.2 单向链表是否有环
使用快慢指针的思想,还是把链表比作一条跑道,链表中有环,那么这条跑道就是一条圆环跑道,在一条圆环跑道中,两个人有速度差,那么迟早两个人会相遇,只要相遇那么就说明有环。 ```java package com.ycc.data.structure.test;
public class CircleListCheckTest { public static void main(String[] args) throws Exception {
//创建结点Node<String> node1 = new Node<>("aa", null);Node<String> node2 = new Node<>("bb", null);Node<String> node3 = new Node<>("cc", null);Node<String> node4 = new Node<>("dd", null);Node<String> node5 = new Node<>("ee", null);Node<String> node6 = new Node<>("ff", null);Node<String> node7 = new Node<>("gg", null);//完成结点之间的指向node1.next = node2;node2.next = node3;node3.next = node4;node4.next = node5;node5.next = node6;node6.next = node7;//产生环node7.next = node3;//判断链表是否有环boolean circle = isCircle(node1);System.out.println("first链表中是否有环:" + circle);}/*** 判断链表中是否有环** @param first 链表首结点* @return ture为有环,false为无环*/public static boolean isCircle(Node<String> first) {//定义快慢指针Node<String> fast = first;Node<String> slow = first;//遍历链表,如果快慢指针指向了同一个结点,那么证明有环while (fast != null && fast.next != null) {//变换fast和slowfast = fast.next.next;slow = slow.next;if (fast.equals(slow)) {return true;}}return false;}//结点类private static class Node<T> {//存储数据T item;//下一个结点Node next;public Node(T item, Node next) {this.item = item;this.next = next;}}
}
<a name="pikGj"></a>### 4.2.3 有环链表入口问题当快慢指针相遇时,我们可以判断到链表中有环,这时重新设定一个新指针指向链表的起点,且步长与慢指针一样为1,则慢指针与“新”指针相遇的地方就是环的入```javapackage com.ycc.data.structure.test;/*** @author liaozx* @date 2020/11/23*/public class CircleListInTest {public static void main(String[] args) throws Exception {//创建结点Node<String> node1 = new Node<>("aa", null);Node<String> node2 = new Node<>("bb", null);Node<String> node3 = new Node<>("cc", null);Node<String> node4 = new Node<>("dd", null);Node<String> node5 = new Node<>("ee", null);Node<String> node6 = new Node<>("ff", null);Node<String> node7 = new Node<>("gg", null);//完成结点之间的指向node1.next = node2;node2.next = node3;node3.next = node4;node4.next = node5;node5.next = node6;node6.next = node7;//产生环node7.next = node3;//查找环的入口结点Node<String> entrance = getEntrance(node1);System.out.println("first链表中环的入口结点元素为:" + entrance.item);}/*** 查找有环链表中环的入口结点** @param first 链表首结点* @return 环的入口结点*/public static Node getEntrance(Node<String> first) {//定义快慢指针Node<String> fast = first;Node<String> slow = first;Node<String> temp = null;//遍历链表,先找到环(快慢指针相遇),准备一个临时指针,指向链表的首结点,继续遍历,直到慢指针和临时指针相遇,那么相遇时所指向的结点就是环的入口while (fast != null && fast.next != null) {//变换快慢指针fast = fast.next.next;slow = slow.next;//判断快慢指针是否相遇if (fast.equals(slow)) {temp = first;continue;}//让临时结点变换if (temp != null) {temp = temp.next;//判断临时指针是否和慢指针相遇if (temp.equals(slow)) {break;}}}return temp;}//结点类private static class Node<T> {//存储数据T item;//下一个结点Node next;public Node(T item, Node next) {this.item = item;this.next = next;}}}
4.3 循环链表
循环链表,顾名思义,链表整体要形成一个圆环状。在单向链表中,最后一个节点的指针为null,不指向任何结点,因为没有下一个元素了。要实现循环链表,我们只需要让单向链表的最后一个节点的指针指向头结点即可。
4.4 约瑟夫问题
public class JosephTest {public static void main(String[] args) {//解决约瑟夫问题//1.构建循环链表,包含41个结点,分别存储1~41之间的值//用来就首结点Node<Integer> first = null;//用来记录前一个结点Node<Integer> pre = null;for (int i = 1; i <= 41; i++) {//如果是第一个结点if (i == 1) {first = new Node<>(i, null);pre = first;continue;}//如果不是第一个结点Node<Integer> newNode = new Node<>(i, null);pre.next = newNode;pre = newNode;//如果是最后一个结点,那么需要让最后一个结点的下一个结点变为first,变为循环链表了if (i == 41) {pre.next = first;}}//2.需要count计数器,模拟报数int count = 0;//3.遍历循环链表//记录每次遍历拿到的结点,默认从首结点开始Node<Integer> n = first;//记录当前结点的上一个结点Node<Integer> before = null;while (n != n.next) {//模拟报数count++;//判断当前报数是不是为3if (count == 3) {//如果是3,则把当前结点删除调用,打印当前结点,重置count=0,让当前结点n后移before.next = n.next;System.out.print(n.item + ",");count = 0;n = n.next;} else {//如果不是3,让before变为当前结点,让当前结点后移;before = n;n = n.next;}}//打印最后一个元素System.out.println(n.item);}//结点类private static class Node<T> {//存储数据T item;//下一个结点Node next;public Node(T item, Node next) {this.item = item;this.next = next;}}}
五 栈
栈是一种基于先进后出(FILO)的数据结构,是一种只能在一端进行插入和删除操作的特殊线性表。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)。我们称数据进入到栈的动作为压栈,数据从栈中出去的动作为弹栈。
5.1 代码实现
顺序结构的栈
package com.ycc.data.structure.line;/*** @author liaozx* @description* @create 2020-11-24 10:45*/public class MyArrayStack<E> {/*** 用来保存数据线性表*/private final MyArrayList<E> list = new MyArrayList<E>();/*** 表示当前栈元素个数*/private int size;/*** 入栈操作** @param e*/public void push(E e) {list.add(e);size++;}/*** 出栈操作** @return*/public E pop() {E e = list.get(size - 1);list.remove(size - 1);size--;return e;}public boolean isEmpty() {return size == 0;}}
链表结构的栈
package com.ycc.data.structure.line;/*** @author liaozx* @description* @create 2020-11-24 10:45*/public class MyLinedStack<E> {/*** 用来保存数据线性表*/private final MyLinedList<E> list = new MyLinedList<E>();/*** 表示当前栈元素个数*/private int size;/*** 入栈操作** @param e*/public void push(E e) {list.add(e);size++;}/*** 出栈操作** @return*/public E pop() {E e = list.get(size - 1);list.remove(size - 1);size--;return e;}public boolean isEmpty() {return size == 0;}}
5.2 测试代码
package com.ycc.data.structure.test;import com.alibaba.fastjson.JSONObject;import com.ycc.data.structure.line.MyArrayStack;import com.ycc.data.structure.line.MyLinedStack;/*** @author liaozx* @date 2020/9/14*/public class MyStackTest {public static void main(String[] args) {//创建栈对象MyArrayStack<String> stack = new MyArrayStack<>();//测试压栈stack.push("a");stack.push("b");stack.push("c");stack.push("d");System.out.println("---stack---" + JSONObject.toJSONString(stack));//测试弹栈String result = stack.pop();System.out.println("弹出的元素是:" + result);//创建栈对象MyLinedStack<String> myLinedStack = new MyLinedStack<>();//测试压栈myLinedStack.push("a");myLinedStack.push("b");myLinedStack.push("c");myLinedStack.push("d");System.out.println("---stack---" + JSONObject.toJSONString(myLinedStack));//测试弹栈String string = myLinedStack.pop();System.out.println("弹出的元素是:" + string);}}
5.3 栈应用-匹配括弧
- 创建一个栈用来存储左括号
- 从左往右遍历字符串,拿到每一个字符
- 判断该字符是不是左括号,如果是,放入栈中存储
- 判断该字符是不是右括号,如果不是,继续下一次循环
- 如果该字符是右括号,则从栈中弹出一个元素t;
- 判断元素t是否为null,如果不是,则证明有对应的左括号,如果不是,则证明没有对应的左括号
- 循环结束后,判断栈中还有没有剩余的左括号,如果有,则不匹配,如果没有,则匹配 ```java package com.ycc.data.structure.test;
import com.ycc.data.structure.line.MyLinedStack;
/**
- @author liaozx
@date 2020-11-24 */ public class MyBracketsMatchTest { public static void main(String[] args) {
String str = "(上海(长安)())";boolean match = isMatch(str);System.out.println(str + "中的括号是否匹配:" + match);
}
/**
- 判断str中的括号是否匹配 *
- @param str 括号组成的字符串
@return 如果匹配,返回true,如果不匹配,返回false */ public static boolean isMatch(String str) { //1.创建栈对象,用来存储左括号 //MyArrayStack
chars = new MyArrayStack<>(); MyLinedStack chars = new MyLinedStack<>(); //2.从左往右遍历字符串 for (int i = 0; i < str.length(); i++) { String currChar = str.charAt(i) + "";//3.判断当前字符是否为左括号,如果是,则把字符放入到栈中if (currChar.equals("(")) {chars.push(currChar);} else if (currChar.equals(")")) {//4.继续判断当前字符是否是有括号,如果是,则从栈中弹出一个左括号,并判断弹出的结果是否为null,如果为null证明没有匹配的左括号,如果不为null,则证明有匹配的左括号if (chars.isEmpty()) {return false;} else {String pop = chars.pop();}}
} //5.判断栈中还有没有剩余的左括号,如果有,则证明括号不匹配 return chars.isEmpty(); } }
<a name="JKQAv"></a>## 5.4 波兰表达式求值1.创建一个栈对象oprands存储操作数<br />2.从左往右遍历逆波兰表达式,得到每一个字符串<br />3.判断该字符串是不是运算符,如果不是,把该该操作数压入oprands栈中<br />4.如果是运算符,则从oprands栈中弹出两个操作数o1,o2<br />5.使用该运算符计算o1和o2,得到结果result<br />6.把该结果压入oprands栈中<br />7.遍历结束后,拿出栈中最终的结果返回```javapackage com.ycc.data.structure.test;import com.ycc.data.structure.line.MyLinedStack;/*** @author liaozx* @date 2020-11-24*/public class ReversePolishNotationTest {public static void main(String[] args) {//中缀表达式 3*(17-15)+18/6 的逆波兰表达式如下 6+3=9String[] expression = {"3", "17", "15", "-", "*", "18", "6", "/", "+"};int result = calculate(expression);System.out.println("逆波兰表达式的结果为:" + result);}/*** @param expression 逆波兰表达式的数组表示方式* @return 逆波兰表达式的计算结果*/public static int calculate(String[] expression) {//1.定义一个栈,用来存储操作数MyLinedStack<Integer> oprands = new MyLinedStack<>();//2.从左往右遍历逆波兰表达式,得到每一个元素for (int i = 0; i < expression.length; i++) {String curr = expression[i];//3.判断当前元素是运算符还是操作数Integer o1;Integer o2;Integer result;switch (curr) {case "+"://4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中o1 = oprands.pop();o2 = oprands.pop();result = o2 + o1;oprands.push(result);break;case "-"://4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中o1 = oprands.pop();o2 = oprands.pop();result = o2 - o1;oprands.push(result);break;case "*"://4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中o1 = oprands.pop();o2 = oprands.pop();result = o2 * o1;oprands.push(result);break;case "/"://4.运算符,从栈中弹出两个操作数,完成运算,运算完的结果再压入栈中o1 = oprands.pop();o2 = oprands.pop();result = o2 / o1;oprands.push(result);break;default://5.操作数,把该操作数放入到栈中;oprands.push(Integer.parseInt(curr));break;}}//6.得到栈中最后一个元素,就是逆波兰表达式的结果int result = oprands.pop();return result;}}
5.5 波兰表达式(补充)
前缀表达式(即波兰表达式)
概念
前缀表达式是一种没有括号的算术表达式,与中缀表达式不同的是,其将运算符写在前面,操作数写在后面。
举例说明
- (3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6
前缀表达式的计算机求值
- 从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 和 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果
前缀表达式求值步骤示例
(3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6
1)、步骤图解如下
2)、步骤描述如下
- 从右至左扫描,将6、5、4、3压入堆栈
- 遇到+运算符,因此弹出3和4(3为栈顶元素,4为次顶元素),计算出3+4的值,得7,再将7入栈
- 接下来是×运算符,因此弹出7和5,计算出7×5=35,将35入栈
- 最后是-运算符,计算出35-6的值,即29,由此得出最终结果
中缀表达式
概念
- 中缀表达式是一个通用的算术或逻辑公式表示方法。
举例说明
- 中缀表达式就是常见的运算表达式,如(3+4)×5-6
中缀表达式的计算机求值
- 中缀表达式的求值是我们人最熟悉的,但是对计算机来说却不好操作,因此,在计算结果时,往往会将中缀表达式转成其它表达式来操作(一般转成后缀表达式.)
后缀表达式(即逆波兰表达式)
概念
- 后缀表达式一般指逆波兰式 ,逆波兰式(Reverse Polish notation,RPN,或逆波兰记法),也叫后缀表达式(将运算符写在操作数之后)
举例说明
- (3+4)×5-6 对应的后缀表达式就是 3 4 + 5 × 6 –

后缀表达式的计算机求值
- 从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 和 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果
后缀表达式求值步骤示例
(3+4)×5-6 对应的后缀表达式就是 3 4 + 5 × 6 -
1)、步骤图解如下

2)、步骤描述如下
- 从左至右扫描,将3和4压入堆栈;
- 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
- 将5入栈;
- 接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
- 将6入栈;
- 最后是-运算符,计算出35-6的值,即29,由此得出最终结果
六 队列
队列是一种基于先进先出(FIFO)的数据结构,是一种只能在一端进行插入,在另一端进行删除操作的特殊线性表,它按照先进先出的原则存储数据,先进入的数据,在读取数据时先读被读出来。
6.1 代码实现
顺序结构的队列
package com.ycc.data.structure.line;/*** @author liaozx* @description* @create 2020-11-24*/public class MyArrayQueue<E> {/*** 用来保存数据的队列*/private final MyArrayList<E> list = new MyArrayList<E>();/*** 表示当前栈元素个数*/private int size;/*** 入队** @param e*/public void enQueue(E e) {list.add(e);size++;}/*** 出队** @return*/public E deQueue() {if (size > 0) {E e = list.get(0);list.remove(0);return e;} else {throw new RuntimeException("已经到达队列顶部");}}}
链表结构的队列
package com.ycc.data.structure.line;/*** @author liaozx* @description* @create 2020-11-24 10:57*/public class MyLinedQueue<E> {private final MyLinedList<E> list = new MyLinedList<E>();// 用来保存数据的队列private int size;// 表示当前栈元素个数/*** 入队** @param e*/public void enQueue(E e) {list.add(e);size++;}/*** 出队** @return*/public E deQueue() {if (size > 0) {E e = list.get(0);list.remove(0);return e;} else {throw new RuntimeException("已经到达队列顶部");}}}
6.2 测试代码
package com.ycc.data.structure.test;import com.ycc.data.structure.line.MyArrayQueue;import com.ycc.data.structure.line.MyLinedQueue;/*** @author liaozx* @date 2020/11/24*/public class MyQueueTest {public static void main(String[] args) {//创建队列对象MyArrayQueue<String> myArrayQueue = new MyArrayQueue<>();//测试队列的enqueue方法myArrayQueue.enQueue("a");myArrayQueue.enQueue("b");myArrayQueue.enQueue("c");myArrayQueue.enQueue("d");System.out.println("-------------------------------");//测试队列的dequeue方法String result = myArrayQueue.deQueue();System.out.println("出队列的元素是:" + result);//创建队列对象MyLinedQueue<String> myLinedQueue = new MyLinedQueue<>();//测试队列的enqueue方法myLinedQueue.enQueue("a");myLinedQueue.enQueue("b");myLinedQueue.enQueue("c");myLinedQueue.enQueue("d");System.out.println("-------------------------------");//测试队列的dequeue方法String string = myLinedQueue.deQueue();System.out.println("出队列的元素是:" + string);}}
七 符号表
符号表最主要的目的就是将一个键和一个值联系起来,符号表能够将存储的数据元素是一个键和一个值共同组成的键值对数据,我们可以根据键来查找对应的值。
7.1 无序符号表
7.1.1 代码实现
package com.ycc.data.structure.line;/*** 链表结构的符号表* 无序** @author liaozx* @date 2020/11/24*/public class MySymbolTable<Key, Value> {//记录首结点private Node head;//记录符号表中元素的个数private int current;private class Node {//键public Key key;//值public Value value;//下一个结点public Node next;public Node(Key key, Value value, Node next) {this.key = key;this.value = value;this.next = next;}}public MySymbolTable() {this.head = new Node(null, null, null);this.current = 0;}//获取符号表中键值对的个数public int size() {return current;}//往符号表中插入键值对public void put(Key key, Value value) {//符号表中已经存在了键为key的键值对,那么只需要找到该结点,替换值为value即可Node node = head;while (node.next != null) {//变换nodenode = node.next;//判断n结点存储的键是否为key,如果是,则替换变换node结点的值if (node.key.equals(key)) {node.value = value;return;}}//如果符号表中不存在键为key的键值对,只需要创建新的结点,保存要插入的键值对,把新结点插入到链表的头部 head.next=新结点即可Node newNode = new Node(key, value, null);//头部第一个有效节点Node oldFirst = head.next;newNode.next = oldFirst;head.next = newNode;//元素个数+1;current++;}//删除符号表中键为key的键值对public void delete(Key key) {//找到键为key的结点,把该结点从链表中删除Node node = head;while (node.next != null) {//判断node结点的下一个结点的键是否为key,如果是,就删除该结点if (node.next.key.equals(key)) {node.next = node.next.next;current--;return;}//变换nodenode = node.next;}}//从符号表中获取key对应的值public Value get(Key key) {//找到键为key的结点Node node = head;while (node.next != null) {//变换nnode = node.next;if (node.key.equals(key)) {return node.value;}}return null;}}
7.1.2 测试代码
package com.ycc.data.structure.test;import com.ycc.data.structure.line.MySymbolTable;/*** @author liaozx* @date 2020/11/24*/public class MySymbolTableTest {public static void main(String[] args) {//创建符号表对象MySymbolTable<Integer, String> symbolTable = new MySymbolTable<>();//测试put方法(插入,替换)symbolTable.put(1, "yanyulou1");symbolTable.put(2, "yanyulou2");symbolTable.put(3, "yanyulou3");symbolTable.put(2, "yanyulou4");System.out.println("替换完毕后的元素的个数为:" + symbolTable.size());//测试get方法System.out.println("替换完毕后,键2对应的值为:" + symbolTable.get(2));//测试删除方法symbolTable.delete(2);System.out.println("删除完毕后,元素的个数:" + symbolTable.size());}}
7.2 有序符号表
7.2.1 代码实现
package com.ycc.data.structure.line;/*** @author liaozx* @date 2020/11/24*/public class MyOrderSymbolTable<Key extends Comparable<Key>, Value> {//记录首结点private Node head;//记录符号表中元素的个数private int current;private class Node {//键public Key key;//值public Value value;//下一个结点public Node next;public Node(Key key, Value value, Node next) {this.key = key;this.value = value;this.next = next;}}public MyOrderSymbolTable() {this.head = new Node(null, null, null);this.current = 0;}//获取符号表中键值对的个数public int size() {return current;}//往符号表中插入键值对public void put(Key key, Value value) {//定义两个Node变量,分别记录当前结点和当前结点的上一个结点Node curr = head.next;Node pre = head;//1.如果key大于当前结点的key,则一直寻找下一个结点while (curr != null && key.compareTo(curr.key) > 0) {//变换当前结点和前一个结点即可pre = curr;curr = curr.next;}//如果当前结点curr的键和要插入的key一样,则替换if (curr != null && key.compareTo(curr.key) == 0) {curr.value = value;return;}//如果当前结点curr的键和要插入的key不一样,把新的结点插入到curr之前Node newNode = new Node(key, value, curr);pre.next = newNode;//元素的个数+1;current++;}//删除符号表中键为key的键值对public void delete(Key key) {//找到键为key的结点,把该结点从链表中删除Node node = head;while (node.next != null) {//判断n结点的下一个结点的键是否为key,如果是,就删除该结点if (node.next.key.equals(key)) {node.next = node.next.next;current--;return;}//变换nnode = node.next;}}//从符号表中获取key对应的值public Value get(Key key) {//找到键为key的结点Node node = head;while (node.next != null) {//变换nnode = node.next;if (node.key.equals(key)) {return node.value;}}return null;}}
7.2.2 测试代码
package com.ycc.data.structure.test;import com.ycc.data.structure.line.MyOrderSymbolTable;/*** @author liaozx* @date 2020/11/24*/public class MyOrderSymbolTableTest {public static void main(String[] args) {//创建有序符号表对象MyOrderSymbolTable<Integer, String> table = new MyOrderSymbolTable<>();table.put(1, "张1");table.put(2, "张2");table.put(4, "张4");table.put(7, "张7");table.put(3, "张3");System.out.println("table" + table);}}
7.3 跳跃表
跳跃表(SkipList)是一种可以替代平衡树的数据结构。跳跃表让已排序的数据分布在多层次的链表结构中,默认是将 Key值升序排列的,以0-1 的随机值决定一个数据是否能够攀升到高层次的链表中。它通过容许一定的数据冗余,达到 “以空间换时间” 的目的。跳跃表的效率和AVL相媲美,查找、添加、插入、删除操作都能够在 O(LogN) 的复杂度内完成。

- 一个跳跃表应该有若干个层(Level)链表组成;
- 跳跃表中最底层的链表包含所有数据, 每一层链表中的数据都是有序的;
- 如果一个元素X出现在第i层,那么编号比 i 小的层都包含元素 X;
- 第 i 层的元素通过一个指针指向下一层拥有相同值的元素;
- 在每一层中,-∞ 和 +∞ 两个元素都出现(分别表示 INT_MIN 和 INT_MAX);
- 头指针(head)指向最高一层的第一个元素;
7.3.1 代码实现
主要实现功能:
- get(Integer key) : 根据 key 值查找某个元素
- put(Integer key, Object value) :插入一个新的元素,元素已存在时为修改操作
- remove(Integer key): 根据 key 值删除某个元素 ```java package com.ycc.data.structure.line;
import java.util.Random;
/**
- 跳跃表 *
- @author liaozx
@date 2020/10/24 */ public class MySkipList
{ // 节点数量 private int number; // 节点最大层数 private int height;
// 第一个节点 private SkipListEntry head; // 最后一个节点 private SkipListEntry tail;
private Random random;
private class SkipListEntry
{ // datapublic Integer key;public E value;// linkspublic SkipListEntry up;public SkipListEntry down;public SkipListEntry left;public SkipListEntry right;// constructorpublic SkipListEntry(Integer key, E value) {this.key = key;this.value = value;}
}
public MySkipList() {
// 创建 head 节点this.head = new SkipListEntry(Integer.MIN_VALUE, null);// 创建 tail 节点this.tail = new SkipListEntry(Integer.MAX_VALUE, null);// 将 head 节点的右指针指向 tail 节点this.head.right = tail;// 将 tail 节点的左指针指向 head 节点this.tail.left = head;this.height = 0;this.number = 0;this.random = new Random();
}
public Object get(Integer key) {
SkipListEntry p = findEntry(key);if (p.key.equals(key)) {return p.value;} else {return null;}
}
public Object put(Integer key, Object value) {
SkipListEntry p, q;int i = 0;// 查找适合插入的位子p = findEntry(key);// 如果跳跃表中存在含有key值的节点,则进行value的修改操作即可完成if (p.key.equals(key)) {Object oldValue = p.value;p.value = value;return oldValue;}// 如果跳跃表中不存在含有key值的节点,则进行新增操作q = new SkipListEntry(key, value);q.left = p;q.right = p.right;p.right.left = q;p.right = q;// 再使用随机数决定是否要向更高level攀升 , 抛硬币, 50% 概率while (random.nextDouble() < 0.5) {// 如果新元素的级别已经达到跳跃表的最大高度,则新建空白层if (i >= height) {addEmptyLevel();}//从p向左扫描含有高层节点的节点while (p.up == null) {p = p.left;}p = p.up;// 新增和q指针指向的节点含有相同key值的节点对象// 这里需要注意的是除底层节点之外的节点对象是不需要value值的SkipListEntry z = new SkipListEntry(key, null);z.left = p;z.right = p.right;p.right.left = z;p.right = z;z.down = q;q.up = z;q = z;i = i + 1;}number = number + 1;// 返回null,没有旧节点的value值return null;
}
public Object remove(Integer key) {
SkipListEntry p, q;p = findEntry(key);if (!p.key.equals(key)) {return null;}Object oldValue = p.value;while (p != null) {q = p.up;p.left.right = p.right;p.right.left = p.left;p = q;}return oldValue;
}
/*** 创建新的空索引层*/private void addEmptyLevel() {SkipListEntry p1, p2;p1 = new SkipListEntry(Integer.MIN_VALUE, null);p2 = new SkipListEntry(Integer.MAX_VALUE, null);p1.right = p2;p1.down = head;p2.left = p1;p2.down = tail;head.up = p1;tail.up = p2;head = p1;tail = p2;height = height + 1;}private SkipListEntry findEntry(Integer key) {// 从head头节点开始查找SkipListEntry p = head;while (true) {// 从左向右查找,直到右节点的key值大于要查找的key值while (p.right.key <= key) {p = p.right;}// 如果有更低层的节点,则向低层移动if (p.down != null) {p = p.down;} else {break;}}// 返回p,!注意这里p的key值是小于等于传入key的值的(p.key <= key)return p;}
}
<a name="M6f9V"></a>### 7.3.2 测试代码```javapackage com.ycc.data.structure.test;import com.ycc.data.structure.line.MySkipList;/*** @author liaozx* @date 2020/11/24*/public class MySkipListTest {public static void main(String[] args) {MySkipList mySkipList = new MySkipList();mySkipList.put(1, "yanyu0");mySkipList.put(2, "yanyu1");mySkipList.put(3, "yanyu2");mySkipList.put(4, "yanyu3");mySkipList.put(5, "yanyu4");mySkipList.put(6, "yanyu5");System.out.println("mySkipList" + mySkipList);}}
