前言:

一 线性表

线性表是最基本、最简单、也是最常用的一种数据结构。一个线性表是由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的后继元素。
image.png
线性表的分类:
线性表中的数据物理存储方式可分为顺序存储、链式存储,即线性表分为顺序表和链表。

二 顺序表

顺序表是在计算机内存中以数组的形式保存的线性表,线性表的顺序存储是指用一组地址连续的存储单元,依次存储线性表中的各个元素、使得线性表中逻辑结构的数据与物理结构的数据一致(相邻的两个元素逻辑和物理存储单元位置一致)。即通过数据元素物理存储相邻关系来反映数据元素逻辑上相邻关系。

2.1 代码实现

关键代码:

  1. add添加元素
  2. add重载添加元素
  3. remove 移除元素
  4. ensureCapacity 扩容以及缩容 ```java package com.ycc.data.structure.line;

import java.util.Iterator;

/**

  • 顺序表 *
  • @author 何兆明
  • @description
  • @create 2019-04-09 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) {

      1. 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++) {
       elementData[i] = elementData[i + 1];
      
      } current—; ensureCapacity(); return (E) temp; }
/**
 * 确认系统当前容量是否满足需要,如果满足,则不执行操作 如果不满足,增加容量
 */
private void ensureCapacity() {
    boolean isResize = false;
    //扩容 默认扩展2倍
    if (current == capacity) {
        capacity = capacity * 2;
        isResize = true;
    }

    //缩容 当数据量小于 容量的1/4 则需要缩容成1/2
    if (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);
    }
}


@Override
public Iterator iterator() {
    return new MyArrayListIterator();
}

//实现迭代器
private class MyArrayListIterator implements Iterator {

    private int curr;

    public MyArrayListIterator() {
        curr = 0;
    }

    @Override
    public boolean hasNext() {
        return curr < current;
    }

    @Override
    public Object next() {
        return elementData[curr++];
    }
}

}

测试代码
```java
package com.ycc.data.structure.test;

import com.alibaba.fastjson.JSONObject;
import com.ycc.data.structure.line.MyArrayList;

/**
 * @author hezhaoming
 * @date 2020/9/13
 */
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 时间复杂度分析

  1. 查询某个元素: get(i): 只需要一次eles[i]就可以获取到对应的元素,所以时间复杂度为O(1);
  2. add(int i,T t):每一次插入,都需要把i位置后面的元素移动一次,随着元素数量N的增大,移动的元素也越多,时间复杂为O(n);
  3. remove(int i):每一次删除,都需要把i位置后面的元素移动一次,随着数据量N的增大,移动的元素也越多,时间复杂度为O(n);

PS: 扩容导致性能下降
顺序表的底层由数组实现,且数组长度是固定的,所以在操作过程中涉及到容器扩容操作。这样会导致顺序表在使用过程中时间复杂度不是线性的,因为它在某些时刻需要扩容,这时耗时会突增,尤其是元素越多,问题越明显。

三 链表

链表是一种物理存储单元上非连续、非顺序的存储结构,其物理结构不能表示元素的逻辑顺序。数据元素的逻辑顺序是通过链表中指针连接实现,即每个结点都有一个指针(next)指向下一个节点。

3.1 单链表代码实现

单向链表是链表中的一种,它由多个结点组成,且每个结点都由一个数据域和一个指针域组成,数据域存储数据,指针域指向其后继结点。链表头结点的数据域不存储数据,指针域指向第一个真正存储数据的结点。
image.png
关键代码:

  1. add 新增元素
  2. add 重载新元素
  3. remove移除元素 ```java package com.ycc.data.structure.line;

import java.util.Iterator;

/**

  • 单向链表 *
  • @author 何兆明
  • @description
  • @create 2019-04-09 22:17 / 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;
    }

    @Override
    public boolean hasNext() {
        return node.next != null;
    }

    @Override
    public Object next() {
        node = node.next;
        return node.item;
    }
}

}

 测试代码
```java
package com.ycc.data.structure.test;

import com.alibaba.fastjson.JSONObject;
import com.ycc.data.structure.line.MyLinedList;

/**
 * @author hezhaoming
 * @date 2020/9/13
 */
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,指向后继结点的指针域指向第一个真正存储数据的结点。
image.png

package com.ycc.data.structure.line;

import java.util.Iterator;

/**
 * 双向链表
 *
 * @author hezhaoming
 * @date 2020/9/14
 */
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) {
            //创建新的结点,即,上一个节点为头节点,下一个为null
            Node newNode = new Node(e, head, null);
            //让新结点称为尾结点
            last = newNode;
            //让头结点指向尾结点
            head.next = last;
        } else {
            Node oldLast = last;
            //创建新的结点,即,上一个节点为last,下一个节点为null
            Node 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;
        //元素的个数+1
        if (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;
        //元素个数-1
        current--;
        //如果删除的是末尾节点则,处理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;
    }

    @Override
    public 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;
        }

        @Override
        public boolean hasNext() {
            return node.next != null;
        }

        @Override
        public 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 hezhaoming
 * @date 2020/9/14
 */
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 时间复杂度分析

  1. get(int i):每次查询要从链表头部开始依次向后查找,数据元素越多,比较就越多,时间复杂度为 O(n)
  2. add(int i,T t):每次插入要先找到i位置的前一个元素,然后完成插入操作,数据元素越多,查找的元素越多,时间复杂度为O(n)
  3. remove(int i):每次移除要先找到i位置的前一个元素,然后完成插入操作,数据元素越多,查找的元素越多,时间复杂度为O(n)

PS:

  1. 增删改快:链表和顺序表虽然操作(插入和删除)复杂度虽然一样,但有很大优势,因为链表物理地址是不连续的,且它不需要预先指定存储空间大小(即不需要扩容+移动拷贝元素)。
  2. 查询慢:所以,查询操作比较多,建议使用顺序表,增删操作比较多,建议使用链表。

    四 链表相关问题

    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;
         //把当前结点的下一个结点变为null
         curr.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和slow
        fast = 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,则慢指针与“新”指针相遇的地方就是环的入
```java
package com.ycc.data.structure.test;

/**
 * @author hezhaoming
 * @date 2020/9/14
 */
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,不指向任何结点,因为没有下一个元素了。要实现循环链表,我们只需要让单向链表的最后一个节点的指针指向头结点即可。
image.png

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++;
            //判断当前报数是不是为3
            if (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)的数据结构,是一种只能在一端进行插入和删除操作的特殊线性表。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)。我们称数据进入到栈的动作为压栈,数据从栈中出去的动作为弹栈。
image.png

5.1 代码实现

顺序结构的栈

package com.ycc.data.structure.line;

/**
 * @author 何兆明
 * @description
 * @create 2019-04-10 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 何兆明
 * @description
 * @create 2019-04-10 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 hezhaoming
 * @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 栈应用-匹配括弧

  1. 创建一个栈用来存储左括号
  2. 从左往右遍历字符串,拿到每一个字符
  3. 判断该字符是不是左括号,如果是,放入栈中存储
  4. 判断该字符是不是右括号,如果不是,继续下一次循环
  5. 如果该字符是右括号,则从栈中弹出一个元素t;
  6. 判断元素t是否为null,如果不是,则证明有对应的左括号,如果不是,则证明没有对应的左括号
  7. 循环结束后,判断栈中还有没有剩余的左括号,如果有,则不匹配,如果没有,则匹配 ```java package com.ycc.data.structure.test;

import com.ycc.data.structure.line.MyLinedStack;

/**

  • @author hezhaoming
  • @date 2020/9/14 */ 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.遍历结束后,拿出栈中最终的结果返回
```java
package com.ycc.data.structure.test;

import com.ycc.data.structure.line.MyLinedStack;

/**
 * @author hezhaoming
 * @date 2020/9/14
 */
public class ReversePolishNotationTest {
    public static void main(String[] args) {
        //中缀表达式 3*(17-15)+18/6 的逆波兰表达式如下 6+3=9
        String[] 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;
    }
}

六 队列

队列是一种基于先进先出(FIFO)的数据结构,是一种只能在一端进行插入,在另一端进行删除操作的特殊线性表,它按照先进先出的原则存储数据,先进入的数据,在读取数据时先读被读出来。
image.png

6.1 代码实现

顺序结构的队列

package com.ycc.data.structure.line;

/**
 * @author 何兆明
 * @description
 * @create 2019-04-10 10:57
 */
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 何兆明
 * @description
 * @create 2019-04-10 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 hezhaoming
 * @date 2020/9/14
 */
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);

    }
}

七 符号表

符号表最主要的目的就是将一个键和一个值联系起来,符号表能够将存储的数据元素是一个键和一个值共同组成的键值对数据,我们可以根据键来查找对应的值。
image.png

7.1 无序符号表

7.1.1 代码实现

package com.ycc.data.structure.line;

/**
 * 链表结构的符号表
 * 无序
 *
 * @author hezhaoming
 * @date 2020/9/14
 */
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) {
            //变换node
            node = 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;
            }
            //变换node
            node = node.next;
        }
    }

    //从符号表中获取key对应的值
    public Value get(Key key) {
        //找到键为key的结点
        Node node = head;
        while (node.next != null) {
            //变换n
            node = 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 hezhaoming
 * @date 2020/9/14
 */
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 hezhaoming
 * @date 2020/9/14
 */
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;
            }
            //变换n
            node = node.next;
        }
    }

    //从符号表中获取key对应的值
    public Value get(Key key) {
        //找到键为key的结点
        Node node = head;
        while (node.next != null) {
            //变换n
            node = 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 hezhaoming
 * @date 2020/9/14
 */
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) 的复杂度内完成。

image.png

  • 一个跳跃表应该有若干个层(Level)链表组成;
  • 跳跃表中最底层的链表包含所有数据, 每一层链表中的数据都是有序的;
  • 如果一个元素X出现在第i层,那么编号比 i 小的层都包含元素 X;
  • 第 i 层的元素通过一个指针指向下一层拥有相同值的元素;
  • 在每一层中,-∞ 和 +∞ 两个元素都出现(分别表示 INT_MIN 和 INT_MAX);
  • 头指针(head)指向最高一层的第一个元素;

节点模型
image.png

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 hezhaoming
  • @date 2020/9/14 */ public class MySkipList {

    // 节点数量 private int number; // 节点最大层数 private int height;

    // 第一个节点 private SkipListEntry head; // 最后一个节点 private SkipListEntry tail;

    private Random random;

    private class SkipListEntry {

     // data
     public Integer key;
     public E value;
    
     // links
     public SkipListEntry up;
     public SkipListEntry down;
     public SkipListEntry left;
     public SkipListEntry right;
    
     // constructor
     public 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 测试代码
```java
package com.ycc.data.structure.test;

import com.ycc.data.structure.line.MySkipList;

/**
 * @author hezhaoming
 * @date 2020/9/14
 */
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);

    }
}