0


六万字数据结构基础知识大总结(含笔试面试习题)

数据结构作为比较难学习的学科来说,它也是我们未来作为程序员必须要牢牢掌握的一门学科,我们应该多画图,多写代码,才能有所收获,本篇博客可以作为入门级别的教学,里面会有图解和详细的代码,总结的内容即代表个人观点,还有部分数据结构内容没有总结,但足够作为一名数据结构的初学者学习,还有各种大厂的笔试题详解。本篇博客内容较长,建议收藏。如果你认为本篇博客写的不错的话,求点赞,求收藏,制作不易,废话不多说,让我们学起来吧!!!

一、时间复杂度和空间复杂度

1,算法效率

算法效率分析分为两种:第一种是时间效率,第二种是空间效率。时间效率被称为时间复杂度,而空间效率被 称作空间复杂度。 时间复杂度主要衡量的是一个算法的运行速度,而空间复杂度主要衡量一个算法所需要的额 外空间,在计算机发展的早期,计算机的存储容量很小。所以对空间度很是在乎。但是经过计算机行业的 迅速发展,计算机的存储容量已经达到了很高的程度。所以我们如今已经不需要再特别关注一个算法的空间复杂度。

2,时间复杂度

①时间复杂度的概念

时间复杂度的定义:在计算机科学中,算法的时间复杂度是一个函数,它定量描述了该算法的运行时间。一个算法执行所耗费的时间,从理论上说,是不能算出来的,只有你把你的程序放在机器上跑起来,才能知道。但 是我们需要每个算法都上机测试吗?是可以都上机测试,但是这很麻烦,所以才有了时间复杂度这个分析方 式。一个算法所花费的时间与其中语句的执行次数成正比例,算法中的基本操作的执行次数,为算法的时间复杂度。

②大O的渐进表示法

  1. void func1(int N){
  2. int count = 0;
  3. for (int i = 0; i < N ; i++) {
  4. for (int j = 0; j < N ; j++) {
  5. count++;
  6. }
  7. }
  8. for (int k = 0; k < 2 * N ; k++) {
  9. count++;
  10. }
  11. int M = 10;
  12. while ((M--) > 0) {
  13. count++;
  14. }
  15. System.out.println(count);
  16. }

请计算一下func1基本操作执行了多少次?

Func1 执行的基本操作次数 :

N = 10 F(N) = 130

N = 100 F(N) = 10210

N = 1000 F(N) = 1002010

实际中我们计算时间复杂度时,我们其实并不一定要计算精确的执行次数,而只需要大概执行次数,那么这里 我们使用大O的渐进表示法。

大O符号(Big O notation):是用于描述函数渐进行为的数学符号。

推导大O阶方法:

1、用常数1取代运行时间中的所有加法常数。

2、在修改后的运行次数函数中,只保留最高阶项。

3、如果最高阶项存在且不是1,则去除与这个项目相乘的常数。得到的结果就是大O阶。

使用大O的渐进表示法以后,Func1的时间复杂度为:

O(N^2)

N = 10 F(N) = 100

N = 100 F(N) = 10000

N = 1000 F(N) = 1000000

通过上面我们会发现大O的渐进表示法去掉了那些对结果影响不大的项,简洁明了的表示出了执行次数。 另外有些算法的时间复杂度存在最好、平均和最坏情况:

最坏情况:任意输入规模的最大运行次数(上界)

平均情况:任意输入规模的期望运行次数

最好情况:任意输入规模的最小运行次数(下界)

在实际中一般情况关注的是算法的最坏运行情况,所以数组中搜索数据时间复杂度为O(N)

③常见时间复杂度计算举例

  1. void func2(int N) {
  2. int count = 0;
  3. for (int k = 0; k < 2 * N ; k++) {
  4. count++;
  5. }
  6. int M = 10;
  7. while ((M--) > 0) {
  8. count++;
  9. }
  10. System.out.println(count);
  11. }

  1. void func3(int N, int M) {
  2. int count = 0;
  3. for (int k = 0; k < M; k++) {
  4. count++;
  5. }
  6. for (int k = 0; k < N ; k++) {
  7. count++;
  8. }
  9. System.out.println(count);
  10. }

  1. void func4(int N) {
  2. int count = 0;
  3. for (int k = 0; k < 100; k++) {
  4. count++;
  5. }
  6. System.out.println(count);
  7. }

  1. void bubbleSort(int[] array) {
  2. for (int end = array.length; end > 0; end--) {
  3. boolean sorted = true;
  4. for (int i = 1; i < end; i++) {
  5. if (array[i -1] > array[i]) {
  6. Swap(array, i - 1, i);
  7. sorted = false;
  8. }
  9. }
  10. if (sorted == true) {
  11. break;
  12. }
  13. }
  14. }

  1. int binarySearch(int[] array, int value) {
  2. int begin = 0;
  3. int end = array.length - 1;
  4. while (begin <= end) {
  5. int mid = begin + ((end-begin) / 2);
  6. if (array[mid] < value)
  7. begin = mid + 1;
  8. else if (array[mid] > value)
  9. end = mid - 1;
  10. else
  11. return mid;
  12. }
  13. return -1;
  14. }

  1. long factorial(int N) {
  2. return N < 2 ? N : factorial(N-1) * N;
  3. }

  1. // 计算斐波那契递归fibonacci的时间复杂度?
  2. int fibonacci(int N) {
  3. return N < 2 ? N : fibonacci(N-1)+fibonacci(N-2);
  4. }

3,空间复杂度

空间复杂度是对一个算法在运行过程中临时占用存储空间大小的量度 。空间复杂度不是程序占用了多少bytes 的空间,因为这个也没太大意义,所以空间复杂度算的是变量的个数。空间复杂度计算规则基本跟实践复杂度 类似,也使用大O渐进表示法。

  1. // 计算bubbleSort的空间复杂度?
  2. void bubbleSort(int[] array) {
  3. for (int end = array.length; end > 0; end--) {
  4. boolean sorted = true;
  5. for (int i = 1; i < end; i++) {
  6. if (array[i - 1] > array[i]) {
  7. Swap(array, i - 1, i);
  8. sorted = false;
  9. }
  10. }
  11. if (sorted == true) {
  12. break;
  13. }
  14. }
  15. }

使用了常数个额外空间,所以空间复杂度为 O(1)

  1. // 计算fibonacci的空间复杂度?
  2. int[] fibonacci(int n) {
  3. long[] fibArray = new long[n + 1];
  4. fibArray[0] = 0;
  5. fibArray[1] = 1;
  6. for (int i = 2; i <= n ; i++) {
  7. fibArray[i] = fibArray[i - 1] + fibArray [i - 2];
  8. }
  9. return fibArray;
  10. }

动态开辟了N个空间,空间复杂度为 O(N)

  1. // 计算阶乘递归Factorial的时间复杂度?
  2. long factorial(int N) {
  3. return N < 2 ? N : factorial(N-1)*N;
  4. }

递归调用了N次,开辟了N个栈帧,每个栈帧使用了常数个空间。空间复杂度为O(N)


二,线性表(单链表和双链表)

1,概念

线性表(linear list)是n个具有相同特性的数据元素的有限序列。 线性表是一种在实际中广泛使用的数据结构,常见的线性表:顺序表、链表、栈、队列、字符串.

线性表在逻辑上是线性结构,也就说是连续的一条直线。但是在物理结构上并不一定是连续的,线性表在物理上存储 时,通常以数组和链式结构的形式存储。

2,顺序表

①概念

顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数 据的增删查改。

顺序表一般可以分为:

静态顺序表:使用定长数组存储。

动态顺序表:使用动态开辟的数组存储。

静态顺序表适用于确定知道需要存多少数据的场景

静态顺序表的定长数组导致N定大了,空间开多了浪费,开少了不够用

相比之下动态顺序表更灵活, 根据需要动态的分配空间大小。

接口实现

  1. class SeqList {
  2. // 打印顺序表
  3. public void display() {
  4. }
  5. // 在 pos 位置新增元素
  6. public void add(int pos, int data) {
  7. }
  8. // 判定是否包含某个元素
  9. public boolean contains(int toFind) {
  10. return true;
  11. }
  12. // 查找某个元素对应的位置
  13. public int search(int toFind) {
  14. return -1;
  15. }
  16. // 获取 pos 位置的元素
  17. public int getPos(int pos) {
  18. return -1;
  19. }
  20. // 给 pos 位置的元素设为 value
  21. public void setPos(int pos, int value) {
  22. }
  23. //删除第一次出现的关键字key
  24. public void remove(int toRemove) {
  25. }
  26. // 获取顺序表长度
  27. public int size() {
  28. return 0;
  29. }
  30. // 清空顺序表
  31. public void clear() {
  32. }
  33. }

③创建顺序表

  1. public int[] elem;
  2. public int usedSize;//有效的数据个数
  3. public MyArrayList() {
  4. this.elem = new int[10];
  5. }

④打印顺序表

  1. // 打印顺序表
  2. public void display() {
  3. for (int i = 0; i < this.usedSize; i++) {
  4. System.out.print(this.elem[i]+" ");
  5. }
  6. System.out.println();
  7. }

⑤获取顺序表有效长度

  1. // 获取顺序表的有效数据长度
  2. public int size() {
  3. return this.usedSize;
  4. }

⑥在pos位置增加元素

  1. public boolean isFull() {
  2. return this.usedSize == this.elem.length;
  3. }
  1. // 在 pos 位置新增元素
  2. public void add(int pos, int data) {
  3. if(pos < 0 || pos > usedSize) {
  4. System.out.println("pos 位置不合法!");
  5. return;
  6. }
  7. if(isFull()) {
  8. this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
  9. }
  10. //3、
  11. for (int i = this.usedSize-1; i >= pos ; i--) {
  12. this.elem[i+1] = this.elem[i];
  13. }
  14. this.elem[pos] = data;
  15. this.usedSize++;
  16. }
  1. public static void main(String[] args) {
  2. MyArrayList myArrayList = new MyArrayList();
  3. myArrayList.add(0,1);
  4. myArrayList.add(1,2);
  5. myArrayList.add(2,3);
  6. myArrayList.add(3,4);
  7. myArrayList.display();
  8. }

⑦判断是否由某个元素、查找某个元素对应的位置,找不到返回-1

  1. // 判定是否包含某个元素
  2. public boolean contains(int toFind) {
  3. for (int i = 0; i < this.usedSize; i++) {
  4. if(this.elem[i] == toFind) {
  5. return true;
  6. }
  7. }
  8. return false;
  9. }
  1. public int search(int toFind) {
  2. for (int i = 0; i < this.usedSize; i++) {
  3. if(this.elem[i] == toFind) {
  4. return i;
  5. }
  6. }
  7. return -1;
  8. }

获取 pos 位置的元素、给 pos 位置的元素设为/更新 value

  1. public int getPos(int pos) {
  2. if(pos < 0 || pos >= this.usedSize) {
  3. System.out.println("pos 位置不合法");
  4. return -1;//所以 这里说明一下,业务上的处理,这里不考虑 后期可以抛异常
  5. }
  6. if(isEmpty()) {
  7. System.out.println("顺序表为空!");
  8. return -1;
  9. }
  10. return this.elem[pos];
  11. }
  1. public boolean isEmpty() {
  2. return this.usedSize==0;
  3. }
  1. public void setPos(int pos, int value) {
  2. if(pos < 0 || pos >= this.usedSize) {
  3. System.out.println("pos位置不合法");
  4. return;
  5. }
  6. if(isEmpty()) {
  7. System.out.println("顺序表为空!");
  8. return;
  9. }
  10. this.elem[pos] = value;
  11. }

⑨删除第一次出现的关键字key

  1. public void remove(int toRemove) {
  2. if(isEmpty()) {
  3. System.out.println("顺序表为空!");
  4. return;
  5. }
  6. int index = search(toRemove);
  7. if(index == -1) {
  8. System.out.println("没有你要删除的数字!");
  9. return;
  10. }
  11. for (int i = index; i < this.usedSize-1; i++) {
  12. this.elem[i] = this.elem[i+1];
  13. }
  14. this.usedSize--;
  15. //this.elem[usedSize] = null; 如果数组当中是引用数据类型。
  16. }
  1. public static void main(String[] args) {
  2. MyArrayList myArrayList = new MyArrayList();
  3. myArrayList.add(0,1);
  4. myArrayList.add(1,2);
  5. myArrayList.add(2,3);
  6. myArrayList.add(3,4);
  7. myArrayList.remove(3);
  8. myArrayList.display();
  9. }

3,链表

①概念

链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的 。

链表分类

②链表的实现

  1. // 1、无头单向非循环链表实现
  2. public class SingleLinkedList {
  3. //头插法
  4. }
  5. public void addFirst(int data){
  6. //尾插法
  7. }
  8. public void addLast(int data){
  9. //任意位置插入,第一个数据节点为0号下标
  10. }
  11. public boolean addIndex(int index,int data){
  12. //查找是否包含关键字key是否在单链表当中
  13. }
  14. public boolean contains(int key){
  15. //删除第一次出现关键字为key的节点
  16. }
  17. public void remove(int key){
  18. //删除所有值为key的节点
  19. }
  20. public void removeAllKey(int key){
  21. //得到单链表的长度
  22. }
  23. public int size(){
  24. }
  25. public void display(){
  26. }
  27. public void clear(){
  28. }
  29. }

③创建节点

  1. public ListNode head;//链表的头引用
  1. lass ListNode {
  2. public int val;
  3. public ListNode next;//null
  4. public ListNode(int val) {
  5. this.val = val;
  6. }

④创建链表、打印链表

  1. public void createList() {
  2. ListNode listNode1 = new ListNode(12);
  3. ListNode listNode2 = new ListNode(23);
  4. ListNode listNode3 = new ListNode(34);
  5. ListNode listNode4 = new ListNode(45);
  6. ListNode listNode5 = new ListNode(56);
  7. listNode1.next = listNode2;
  8. listNode2.next = listNode3;
  9. listNode3.next = listNode4;
  10. listNode4.next = listNode5;
  11. //listNode5.next = null;
  12. this.head = listNode1;
  13. }
  1. public void display() {
  2. //this.head.next != null
  3. ListNode cur = this.head;
  4. while (cur != null) {
  5. System.out.print(cur.val+" ");
  6. cur = cur.next;
  7. }
  8. System.out.println();
  9. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. //myLinkedList.createList();
  4. myLinkedList.addLast(12);
  5. myLinkedList.addLast(23);
  6. myLinkedList.addLast(34);
  7. myLinkedList.addLast(45);
  8. myLinkedList.addLast(56);
  9. myLinkedList.display();
  10. }

⑤查找是否包含关键字key是否在单链表当中、得到单链表的长度

  1. public boolean contains(int key){
  2. ListNode cur = this.head;
  3. while (cur != null) {
  4. if(cur.val == key) {
  5. return true;
  6. }
  7. cur = cur.next;
  8. }
  9. return false;
  10. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. //myLinkedList.createList();
  4. myLinkedList.addLast(12);
  5. myLinkedList.addLast(23);
  6. myLinkedList.addLast(34);
  7. myLinkedList.addLast(45);
  8. myLinkedList.addLast(56);
  9. myLinkedList.display();
  10. boolean flg = myLinkedList.contains(56);
  11. }
  1. public int size(){
  2. int count = 0;
  3. ListNode cur = this.head;
  4. while (cur != null) {
  5. count++;
  6. cur = cur.next;
  7. }
  8. return count;
  9. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. //myLinkedList.createList();
  4. myLinkedList.addLast(12);
  5. myLinkedList.addLast(23);
  6. myLinkedList.addLast(34);
  7. myLinkedList.addLast(45);
  8. myLinkedList.addLast(56);
  9. System.out.println(myLinkedList.size());
  10. }

** ⑥头插法、尾插法**

  1. //头插法
  2. public void addFirst(int data){
  3. ListNode node = new ListNode(data);
  4. node.next = this.head;
  5. this.head = node;
  6. /*if(this.head == null) {
  7. this.head = node;
  8. }else {
  9. node.next = this.head;
  10. this.head = node;
  11. }*/
  12. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. //myLinkedList.createList();
  4. myLinkedList.addLast(12);
  5. myLinkedList.addLast(23);
  6. myLinkedList.addLast(34);
  7. myLinkedList.addLast(45);
  8. myLinkedList.addLast(56);
  9. myLinkedList.addFirst(10);
  10. myLinkedList.display();
  11. }

  1. //尾插法
  2. public void addLast(int data){
  3. ListNode node = new ListNode(data);
  4. if(this.head == null) {
  5. this.head = node;
  6. }else {
  7. ListNode cur = this.head;
  8. while (cur.next != null) {
  9. cur = cur.next;
  10. }
  11. //cur.next == null;
  12. cur.next = node;
  13. }
  14. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. //myLinkedList.createList();
  4. myLinkedList.addLast(12);
  5. myLinkedList.addLast(23);
  6. myLinkedList.addLast(34);
  7. myLinkedList.addLast(45);
  8. myLinkedList.addLast(56);
  9. myLinkedList.addLast(90);
  10. myLinkedList.display();
  11. }

⑦找到index-1位置的节点的地址、插入元素

  1. public ListNode findIndex(int index) {
  2. ListNode cur = this.head;
  3. while (index-1 != 0) {
  4. cur = cur.next;
  5. index--;
  6. }
  7. return cur;
  8. }

  1. //任意位置插入,第一个数据节点为0号下标
  2. public void addIndex(int index,int data){
  3. if(index < 0 || index > size()) {
  4. System.out.println("index位置不合法!");
  5. return;
  6. }
  7. if(index == 0) {
  8. addFirst(data);
  9. return;
  10. }
  11. if(index == size()) {
  12. addLast(data);
  13. return;
  14. }
  15. ListNode cur = findIndex(index);
  16. ListNode node = new ListNode(data);
  17. node.next = cur.next;
  18. cur.next = node;
  19. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. //myLinkedList.createList();
  4. myLinkedList.addLast(12);
  5. myLinkedList.addLast(23);
  6. myLinkedList.addLast(34);
  7. myLinkedList.addLast(45);
  8. myLinkedList.addLast(56);
  9. myLinkedList.addLast(90);
  10. myLinkedList.addIndex(2,20);
  11. myLinkedList.display();
  12. }

⑧找到要删除的关键字的前驱、删除第一次出现关键字为key的节点

  1. public ListNode searchPerv(int key) {
  2. ListNode cur = this.head;
  3. while (cur.next != null) {
  4. if(cur.next.val == key) {
  5. return cur;
  6. }
  7. cur = cur.next;
  8. }
  9. return null;
  10. }

  1. //删除第一次出现关键字为key的节点
  2. public void remove(int key){
  3. if(this.head == null) {
  4. System.out.println("单链表为空,不能删除!");
  5. return;
  6. }
  7. if(this.head.val == key) {
  8. this.head = this.head.next;
  9. return;
  10. }
  11. ListNode cur = searchPerv(key);
  12. if(cur == null) {
  13. System.out.println("没有你要删除的节点!");
  14. return;
  15. }
  16. ListNode del = cur.next;
  17. cur.next = del.next;
  18. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. //myLinkedList.createList();
  4. myLinkedList.addLast(12);
  5. myLinkedList.addLast(23);
  6. myLinkedList.addLast(34);
  7. myLinkedList.addLast(45);
  8. myLinkedList.addLast(56);
  9. myLinkedList.addLast(90);
  10. myLinkedList.remove(23);
  11. myLinkedList.display();
  12. }

删除所有值为key的节点

  1. //删除所有值为key的节点
  2. public ListNode removeAllKey(int key){
  3. if(this.head == null) return null;
  4. ListNode prev = this.head;
  5. ListNode cur = this.head.next;
  6. while (cur != null) {
  7. if(cur.val == key) {
  8. prev.next = cur.next;
  9. cur = cur.next;
  10. }else {
  11. prev = cur;
  12. cur = cur.next;
  13. }
  14. }
  15. //最后处理头
  16. if(this.head.val == key) {
  17. this.head = this.head.next;
  18. }
  19. return this.head;
  20. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. //myLinkedList.createList();
  4. myLinkedList.addLast(12);
  5. myLinkedList.addLast(23);
  6. myLinkedList.addLast(23);
  7. myLinkedList.addLast(23);
  8. myLinkedList.addLast(56);
  9. myLinkedList.addLast(90);
  10. myLinkedList.removeAllKey(23);
  11. myLinkedList.display();
  12. }

清空链表

  1. public void clear(){
  2. //this.head == null
  3. while (this.head != null) {
  4. ListNode curNext = head.next;
  5. this.head.next = null;
  6. this.head = curNext;
  7. }
  8. }

4,双向链表

①链表的实现

  1. public class DoubleLinkedList {
  2. //头插法
  3. public void addFirst(int data){
  4. }
  5. //尾插法
  6. public void addLast(int data){
  7. }
  8. //任意位置插入,第一个数据节点为0号下标
  9. public boolean addIndex(int index,int data){
  10. }
  11. //查找是否包含关键字key是否在单链表当中
  12. public boolean contains(int key){
  13. }
  14. //删除第一次出现关键字为key的节点
  15. public void remove(int key){
  16. }
  17. //删除所有值为key的节点
  18. public void removeAllKey(int key){
  19. }
  20. //得到单链表的长度
  21. public int size(){
  22. }
  23. public void display(){
  24. }
  25. public void clear(){
  26. }
  27. }

②构造节点和链表

  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. }
  1. public ListNode head;//指向双向链表的头节点
  2. //public ListNode head = new ListNode(-1);//指向双向链表的头节点
  3. public ListNode last;//指向的是尾巴节点

③打印链表、求链表长度

  1. public void display() {
  2. //和单链表的打印方式是一样的
  3. ListNode cur = this.head;
  4. while (cur != null) {
  5. System.out.print(cur.val+" ");
  6. cur = cur.next;
  7. }
  8. System.out.println();
  9. }
  1. /得到单链表的长度
  2. public int size() {
  3. int count = 0;
  4. ListNode cur = this.head;
  5. while (cur != null) {
  6. count++;
  7. cur = cur.next;
  8. }
  9. return count;
  10. }

④查询key

  1. public boolean contains(int key){
  2. ListNode cur = this.head;
  3. while (cur != null) {
  4. if(cur.val == key) {
  5. return true;
  6. }
  7. cur = cur.next;
  8. }
  9. return false;
  10. }

⑤头插法

  1. //头插法
  2. public void addFirst(int data) {
  3. ListNode node = new ListNode(data);
  4. if(this.head == null) {
  5. this.head = node;
  6. this.last = node;
  7. }else {
  8. node.next = this.head;
  9. this.head.prev = node;
  10. this.head = node;
  11. }
  12. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. myLinkedList.addFirst(12);
  4. myLinkedList.addFirst(23);
  5. myLinkedList.addFirst(34);
  6. myLinkedList.addFirst(45);
  7. myLinkedList.addFirst(56);
  8. myLinkedList.display();
  9. }

⑥尾插法

  1. //尾插法
  2. public void addLast(int data){
  3. ListNode node = new ListNode(data);
  4. if(this.head == null) {
  5. this.head = node;
  6. this.last = node;
  7. }else {
  8. this.last.next = node;
  9. node.prev = this.last;
  10. this.last = node;
  11. }
  12. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. myLinkedList.addLast(12);
  4. myLinkedList.addLast(23);
  5. myLinkedList.addLast(34);
  6. myLinkedList.addLast(45);
  7. myLinkedList.addLast(56);
  8. myLinkedList.display();
  9. }

⑦寻找插入节点

  1. public ListNode searchIndex (int index) {
  2. ListNode cur = this.head;
  3. while (index != 0) {
  4. cur = cur.next;
  5. index--;
  6. }
  7. return cur;
  8. }

⑧插入元素

  1. //任意位置插入,第一个数据节点为0号下标
  2. public void addIndex(int index,int data){
  3. ListNode node = new ListNode(data);
  4. if(index < 0 || index > size()) {
  5. System.out.println("index位置不合法!");
  6. return;
  7. }
  8. if(index == 0) {
  9. addFirst(data);
  10. return;
  11. }
  12. if(index == size()) {
  13. addLast(data);
  14. return;
  15. }
  16. ListNode cur = searchIndex(index);
  17. node.next = cur.prev.next;
  18. cur.prev.next = node;
  19. node.prev = cur.prev;
  20. cur.prev = node;
  21. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. myLinkedList.addLast(12);
  4. myLinkedList.addLast(23);
  5. myLinkedList.addLast(34);
  6. myLinkedList.addLast(45);
  7. myLinkedList.addLast(56);
  8. myLinkedList.display();
  9. myLinkedList.addIndex(3,99);
  10. myLinkedList.display();
  11. }

⑨删除元素

  1. //删除第一次出现关键字为key的节点
  2. public void remove(int key){
  3. ListNode cur = this.head;
  4. while (cur != null) {
  5. if(cur.val == key) {
  6. if(cur == head) {
  7. head = head.next;
  8. if(head != null) {
  9. head.prev = null;
  10. }else {
  11. last = null;
  12. }
  13. }else {
  14. cur.prev.next = cur.next;
  15. if(cur.next != null) {
  16. //中间位置
  17. cur.next.prev = cur.prev;
  18. }else {
  19. last = last.prev;
  20. }
  21. }
  22. return;
  23. }
  24. cur = cur.next;
  25. }
  26. }
  1. public static void main(String[] args) {
  2. MyLinkedList myLinkedList = new MyLinkedList();
  3. myLinkedList.addLast(12);
  4. myLinkedList.addLast(23);
  5. myLinkedList.addLast(34);
  6. myLinkedList.addLast(45);
  7. myLinkedList.addLast(56);
  8. myLinkedList.display();
  9. myLinkedList.remove(23);
  10. myLinkedList.display();
  11. }

⑩清空链表

  1. public void clear() {
  2. while (head != null) {
  3. ListNode curNext = head.next;
  4. head.next = null;
  5. head.prev = null;
  6. head = curNext;
  7. }
  8. last = null;
  9. }

5,笔试习题

反转一个单链表

  1. public ListNode reverseList() {
  2. if(this.head == null) {
  3. return null;
  4. }
  5. ListNode cur = this.head;
  6. ListNode prev = null;
  7. while (cur != null) {
  8. ListNode curNext = cur.next;
  9. cur.next = prev;
  10. prev = cur;
  11. cur = curNext;
  12. }
  13. return prev;
  14. }

给定一个带有头结点 head 的非空单链表,返回链表的中间结点

  1. public ListNode middleNode() {
  2. if(head == null) {
  3. return null;
  4. }
  5. ListNode fast = head;
  6. ListNode slow = head;
  7. while(fast != null && fast.next != null){
  8. fast = fast.next.next;
  9. if(fast == null) {
  10. return slow;
  11. }
  12. slow = slow.next;
  13. }
  14. return slow;
  15. }

③输入一个链表,输出该链表中倒数第k个结点

  1. public ListNode findKthToTail(int k) {
  2. if(k <= 0 || head == null) {
  3. return null;
  4. }
  5. ListNode fast = head;
  6. ListNode slow = head;
  7. while (k-1 != 0) {
  8. fast = fast.next;
  9. if(fast == null) {
  10. return null;
  11. }
  12. k--;
  13. }
  14. while (fast.next != null) {
  15. fast = fast.next;
  16. slow = slow.next;
  17. }
  18. return slow;
  19. }

④删除链表中的多个重复值

  1. //删除所有值为key的节点
  2. public ListNode removeAllKey(int key){
  3. if(this.head == null) return null;
  4. ListNode prev = this.head;
  5. ListNode cur = this.head.next;
  6. while (cur != null) {
  7. if(cur.val == key) {
  8. prev.next = cur.next;
  9. cur = cur.next;
  10. }else {
  11. prev = cur;
  12. cur = cur.next;
  13. }
  14. }
  15. //最后处理头
  16. if(this.head.val == key) {
  17. this.head = this.head.next;
  18. }
  19. return this.head;
  20. }

⑤链表的回文结构

  1. public boolean chkPalindrome(ListNode A) {
  2. // write code here
  3. if(head == null) return true;
  4. ListNode fast = head;
  5. ListNode slow = head;
  6. while(fast != null && fast.next != null) {
  7. fast = fast.next.next;
  8. slow = slow.next;
  9. }
  10. //slow走到了中间位置-》反转
  11. ListNode cur = slow.next;
  12. while(cur != null) {
  13. ListNode curNext = cur.next;
  14. cur.next = slow;
  15. slow = cur;
  16. cur = curNext;
  17. }
  18. //反转完成
  19. while(head != slow) {
  20. if(head.val != slow.val) {
  21. return false;
  22. }
  23. if(head.next == slow) {
  24. return true;
  25. }
  26. head = head.next;
  27. slow = slow.next;
  28. }
  29. return true;
  30. }

⑥合并两个链表

  1. public static ListNode mergeTwoLists(ListNode headA, ListNode headB) {
  2. ListNode newHead = new ListNode(-1);
  3. ListNode tmp = newHead;
  4. while (headA != null && headB != null) {
  5. if(headA.val < headB.val) {
  6. tmp.next = headA;
  7. headA = headA.next;
  8. tmp = tmp.next;
  9. }else {
  10. tmp.next = headB;
  11. headB = headB.next;
  12. tmp = tmp.next;
  13. }
  14. }
  15. if(headA != null) {
  16. tmp.next = headA;
  17. }
  18. if(headB != null) {
  19. tmp.next = headB;
  20. }
  21. return newHead.next;
  22. }

⑦输入两个链表,找出它们的第一个公共结点

  1. public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
  2. if(headA == null || headB == null) {
  3. return null;
  4. }
  5. ListNode pl = headA;
  6. ListNode ps = headB;
  7. int lenA = 0;
  8. int lenB = 0;
  9. while (pl != null) {
  10. lenA++;
  11. pl = pl.next;
  12. }
  13. //pl==null
  14. pl = headA;
  15. while (ps != null) {
  16. lenB++;
  17. ps = ps.next;
  18. }
  19. //ps==null
  20. ps = headB;
  21. int len = lenA-lenB;//差值步
  22. if(len < 0) {
  23. pl = headB;
  24. ps = headA;
  25. len = lenB-lenA;
  26. }
  27. //1、pl永远指向了最长的链表 ps 永远指向了最短的链表 2、求到了差值len步
  28. //pl走差值len步
  29. while (len != 0) {
  30. pl = pl.next;
  31. len--;
  32. }
  33. //同时走 直到相遇
  34. while (pl != ps) {
  35. pl = pl.next;
  36. ps = ps.next;
  37. }
  38. return pl;
  39. }

⑧判断一个链表是否有环

  1. public boolean hasCycle() {
  2. if(head == null) return false;
  3. ListNode fast = head;
  4. ListNode slow = head;
  5. while(fast != null && fast.next != null) {
  6. fast = fast.next.next;
  7. slow = slow.next;
  8. if(fast == slow) {
  9. return true;
  10. }
  11. }
  12. return false;
  13. }

⑨求有环链表的环第一个结点

  1. public ListNode detectCycle(ListNode head) {
  2. if(head == null) return null;
  3. ListNode fast = head;
  4. ListNode slow = head;
  5. while(fast != null && fast.next != null) {
  6. fast = fast.next.next;
  7. slow = slow.next;
  8. if(fast == slow) {
  9. break;
  10. }
  11. }
  12. if(fast == null || fast.next == null) {
  13. return null;
  14. }
  15. fast = head;
  16. while (fast != slow) {
  17. fast = fast.next;
  18. slow = slow.next;
  19. }
  20. return fast;
  21. }

三,栈和队列

1,栈

①概念

在我们软件应用 ,栈这种后进先出数据结构的应用是非常普遍的。比如你用浏 览器上网时不管什么浏览器都有 个"后退"键,你点击后可以接访问顺序的逆序加载浏览过的网页。

很多类似的软件,比如 Word Photoshop 等文档或图像编 软件中 都有撤销 )的操作,也是用栈这种方式来实现的,当然不同的软件具体实现会有很大差异,不过原理其实都是一样的

栈( stack )是限定仅在表尾进行插入和删除的线性表

栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈 顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。

②栈的操作

压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。

出栈:栈的删除操作叫做出栈。出数据在栈顶。

③栈的实现

入栈

  1. public static void main(String[] args) {
  2. Stack<Integer> stack = new Stack<>();
  3. stack.push(1);
  4. stack.push(2);
  5. stack.push(3);
  6. stack.push(4);
  7. int ret = stack.push(4);
  8. System.out.println(ret);
  9. }

出栈

  1. public static void main(String[] args) {
  2. Stack<Integer> stack = new Stack<>();
  3. stack.push(1);
  4. stack.push(2);
  5. stack.push(3);
  6. int ret1 = stack.pop();
  7. int ret2 = stack.pop();
  8. System.out.println(ret1);
  9. System.out.println(ret2);
  10. }

获取栈顶元素

  1. public static void main(String[] args) {
  2. Stack<Integer> stack = new Stack<>();
  3. stack.push(1);
  4. stack.push(2);
  5. stack.push(3);
  6. int ret1 = stack.pop();
  7. int ret2 = stack.pop();
  8. int ret3 = stack.peek();
  9. System.out.println(ret1);
  10. System.out.println(ret2);
  11. System.out.println(ret3);
  12. }

判断栈是否为空

  1. public static void main(String[] args) {
  2. Stack<Integer> stack = new Stack<>();
  3. stack.push(1);
  4. stack.push(2);
  5. stack.push(3);
  6. int ret1 = stack.pop();
  7. int ret2 = stack.pop();
  8. int ret3 = stack.peek();
  9. System.out.println(ret1);
  10. System.out.println(ret2);
  11. System.out.println(ret3);
  12. stack.pop();
  13. boolean flag = stack.empty();
  14. System.out.println(flag);
  15. }

④实现mystack

  1. public class MyStack<T> {
  2. private T[] elem;//数组
  3. private int top;//当前可以存放数据元素的下标-》栈顶指针
  4. public MyStack() {
  5. this.elem = (T[])new Object[10];
  6. }
  7. /**
  8. * 入栈操作
  9. * @param item 入栈的元素
  10. */
  11. public void push(T item) {
  12. //1、判断当前栈是否是满的
  13. if(isFull()){
  14. this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
  15. }
  16. //2、elem[top] = item top++;
  17. this.elem[this.top++] = item;
  18. }
  19. public boolean isFull(){
  20. return this.elem.length == this.top;
  21. }
  22. /**
  23. * 出栈
  24. * @return 出栈的元素
  25. */
  26. public T pop() {
  27. if(empty()) {
  28. throw new UnsupportedOperationException("栈为空!");
  29. }
  30. T ret = this.elem[this.top-1];
  31. this.top--;//真正的改变了top的值
  32. return ret;
  33. }
  34. /**
  35. * 得到栈顶元素,但是不删除
  36. * @return
  37. */
  38. public T peek() {
  39. if(empty()) {
  40. throw new UnsupportedOperationException("栈为空!");
  41. }
  42. //this.top--;//真正的改变了top的值
  43. return this.elem[this.top-1];
  44. }
  45. public boolean empty(){
  46. return this.top == 0;
  47. }
  48. }
  1. public static void main(String[] args) {
  2. MyStack<Integer> myStack = new MyStack<>();
  3. myStack.push(1);
  4. myStack.push(2);
  5. myStack.push(3);
  6. System.out.println(myStack.peek());
  7. System.out.println(myStack.pop());
  8. System.out.println(myStack.pop());
  9. System.out.println(myStack.pop());
  10. System.out.println(myStack.empty());
  11. System.out.println("============================");
  12. MyStack<String> myStack2 = new MyStack<>();
  13. myStack2.push("hello");
  14. myStack2.push("word");
  15. myStack2.push("thank");
  16. System.out.println(myStack2.peek());
  17. System.out.println(myStack2.pop());
  18. System.out.println(myStack2.pop());
  19. System.out.println(myStack2.pop());
  20. System.out.println(myStack2.empty());
  21. }

2,队列

①概念

像移动、联通、电信等客服电话,客服人员与客户相比总是少数,在所有的客服人员都占线的情况下,客户会被要求等待,直到有某个客服人员空下来,才能让最先等待的客户接通电话。这里也是将所有当前拨打客服电话的客户进行了排队处理。

操作系统和客服系统中,都是应用了种数据结构来实现刚才提到的先进先出的排队功能,这就是队列。
队列(queue) 是只允许在一端进行插入操作,而在另一端进行删除操作的线性表

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾(Tail/Rear) 出队列:进行删除操作的一端称为队头 (Head/Front)

②队列的实现

入队

  1. public static void main(String[] args) {
  2. Deque<Integer> queue = new LinkedList<>();
  3. queue.offer(1);
  4. queue.offer(2);
  5. queue.offer(3);
  6. queue.offer(4);
  7. }

出队

  1. public static void main(String[] args) {
  2. Deque<Integer> queue = new LinkedList<>();
  3. queue.offer(1);
  4. queue.offer(2);
  5. queue.offer(3);
  6. queue.offer(4);
  7. System.out.println(queue.poll());
  8. System.out.println(queue.poll());
  9. }

获取队首元素

  1. public static void main(String[] args) {
  2. Deque<Integer> queue = new LinkedList<>();
  3. queue.offer(1);
  4. queue.offer(2);
  5. queue.offer(3);
  6. queue.offer(4);
  7. System.out.println(queue.poll());
  8. System.out.println(queue.poll());
  9. System.out.println("-----------------");
  10. System.out.println(queue.peek());
  11. }

实现myqueue

  1. class Node {
  2. private int val;
  3. private Node next;
  4. public int getVal() {
  5. return val;
  6. }
  7. public void setVal(int val) {
  8. this.val = val;
  9. }
  10. public Node getNext() {
  11. return next;
  12. }
  13. public void setNext(Node next) {
  14. this.next = next;
  15. }
  16. public Node(int val) {
  17. this.val = val;
  18. }
  19. }
  20. public class MyQueue {
  21. private Node first;
  22. private Node last;
  23. //入队
  24. public void offer(int val) {
  25. //尾插法 需要判断是不是第一次插入
  26. Node node = new Node(val);
  27. if(this.first == null) {
  28. this.first = node;
  29. this.last = node;
  30. }else {
  31. this.last.setNext(node);//last.next = node;
  32. this.last = node;
  33. }
  34. }
  35. //出队
  36. public int poll() {
  37. //1判断是否为空的
  38. if(isEmpty()) {
  39. throw new UnsupportedOperationException("队列为空!");
  40. }
  41. //this.first = this.first.next;
  42. int ret = this.first.getVal();
  43. this.first = this.first.getNext();
  44. return ret;
  45. }
  46. //得到队头元素但是不删除
  47. public int peek() {
  48. //不要移动first
  49. if(isEmpty()) {
  50. throw new UnsupportedOperationException("队列为空!");
  51. }
  52. return this.first.getVal();
  53. }
  54. //队列是否为空
  55. public boolean isEmpty() {
  56. return this.first == null;
  57. }
  58. }
  1. public static void main(String[] args) {
  2. MyQueue myQueue = new MyQueue();
  3. myQueue.offer(1);
  4. myQueue.offer(2);
  5. myQueue.offer(3);
  6. System.out.println(myQueue.peek());
  7. System.out.println(myQueue.poll());
  8. System.out.println(myQueue.poll());
  9. System.out.println(myQueue.poll());
  10. System.out.println(myQueue.isEmpty());
  11. }


四,二叉树

1,树

①概念

树是一种非线性的数据结构,它是由n(n>=0)个有限结点组成一个具有层次关系的集合。把它叫做树是因为它看 起来像一棵倒挂的树,也就是说它是根朝上,而叶朝下的。它具有以下的特点:

有一个特殊的节点,称为根节点,根节点没有前驱节点

除根节点外,其余节点被分成M(M > 0)个互不相交的集合T1、T2、......、Tm,其中每一个集合 Ti (1 <= i <= m) 又是一棵与树类似的子树。每棵子树的根节点有且只有一个前驱,可以有0个或多个后继
树是递归定义的

②树的基础概念

节点的度:一个节点含有的子树的个数称为该节点的度

树的度:一棵树中,最大的节点的度称为树的度

叶子节点或终端节点:度为0的节点称为叶节点

双亲节点或父节点:若一个节点含有子节点,则这个节点称为其子节点的父节点

孩子节点或子节点:一个节点含有的子树的根节点称为该节点的子节点

根结点:一棵树中,没有双亲结点的结点

节点的层次:从根开始定义起,根为第1层,根的子节点为第2层,以此类推

树的高度或深度:树中节点的最大层次

2,二叉树

①概念

一棵二叉树是结点的一个有限集合,该集合或者为空,或者是由一个根节点加上两棵别称为左子树和右子树的二叉树组成。

二叉树的特点:

  1. 每个结点最多有两棵子树,即二叉树不存在度大于 2 的结点。

  2. 二叉树的子树有左右之分,其子树的次序不能颠倒,因此二叉树是有序树。

两种特殊的二叉树

  1. 满二叉树: 一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是满二叉树。也就是说,如果 一个二叉树的层数为K,且结点总数是 ,则它就是满二叉树。

  1. 完全二叉树: 完全二叉树是效率很高的数据结构,完全二叉树是由满二叉树而引出来的。对于深度为K的,有n 个结点的二叉树,当且仅当其每一个结点都与深度为K的满二叉树中编号从1至n的结点一一对应时称之为完全 二叉树。 要注意的是满二叉树是一种特殊的完全二叉树。

二叉树的性质

  1. 若规定根节点的层数为1,则一棵非空二叉树的第i层上最多有2^(i-1) (i>0)个结点

  2. 若规定只有根节点的二叉树的深度为1,则深度为K的二叉树的最大结点数是2^k-1 (k>=0)

  3. 对任何一棵二叉树, 如果其叶结点个数为 n0, 度为2的非叶结点个数为 n2,则有n0=n2+1

  4. 具有n个结点的完全二叉树的深度k为log2(n+1)上取整

3,二叉树遍历

①二叉树的遍历

所谓遍历(Traversal)是指沿着某条搜索路线,依次对树中每个结点均做一次且仅做一次访问。访问结点所做的操作 依赖于具体的应用问题(比如:打印节点内容、节点内容加1)。 遍历是二叉树上最重要的操作之一,是二叉树上进 行其它运算之基础。

在遍历二叉树时,如果没有进行某种约定,每个人都按照自己的方式遍历,得出的结果就比较混乱,如果按照某种 规则进行约定,则每个人对于同一棵树的遍历结果肯定是相同的。如果N代表根节点,L代表根节点的左子树,R代 表根节点的右子树,则根据遍历根节点的先后次序有以下遍历方式:

  1. NLR:**前序遍历(Preorder Traversal 亦称先序遍历)**——访问根结点--->根的左子树--->根的右子树。

  1. LNR:**中序遍历(Inorder Traversal)**——根的左子树--->根节点--->根的右子树。

  1. LRN:**后序遍历(Postorder Traversal)**——根的左子树--->根的右子树--->根节点。

由于被访问的结点必是某子树的根,所以N(Node)、L(Left subtree)和R(Right subtree)又可解释为根、根 的左子树和根的右子树。NLR、LNR和LRN分别又称为先根遍历、中根遍历和后根遍历。

注意:三种遍历中只有访问根节点打印,每一种遍历当访问到每一个节点都要有对应三种不同的遍历方式,直到遍历到null返回到该根节点继续完成遍历!!!比如说前序遍历,我每访问一个节点都要执行问根结点--->根的左子树--->根的右子树这三步,中序后序遍历一样。

以下面这个二叉树为例,接下来就是详解

②前序遍历

图解

代码分析

我们用枚举法创建这个二叉树

  1. public TreeNode createTree() {
  2. TreeNode A = new TreeNode('A');
  3. TreeNode B = new TreeNode('B');
  4. TreeNode C = new TreeNode('C');
  5. TreeNode D = new TreeNode('D');
  6. TreeNode E = new TreeNode('E');
  7. TreeNode F = new TreeNode('F');
  8. TreeNode G = new TreeNode('G');
  9. TreeNode H = new TreeNode('H');
  10. A.left = B;
  11. A.right = C;
  12. B.left = D;
  13. B.right = E;
  14. C.left = F;
  15. C.right = G;
  16. E.right = H;
  17. return A;
  18. }
  1. // 前序遍历
  2. void preOrderTraversal(TreeNode root){
  3. if(root == null) {
  4. return;
  5. }
  6. System.out.print(root.val+" ");
  7. preOrderTraversal(root.left);
  8. preOrderTraversal(root.right);
  9. }

DeBug分析

③中序遍历

图解

  1. // 中序遍历
  2. void inOrderTraversal(TreeNode root){
  3. if(root == null) {
  4. return;
  5. }
  6. inOrderTraversal(root.left);
  7. System.out.print(root.val+" ");
  8. inOrderTraversal(root.right);
  9. }

DeBug分析

④后序遍历

图解

  1. // 后序遍历
  2. void postOrderTraversal(TreeNode root){
  3. if(root == null) {
  4. return;
  5. }
  6. postOrderTraversal(root.left);
  7. postOrderTraversal(root.right);
  8. System.out.print(root.val+" ");
  9. }

DeBug分析

3,二叉搜索树

①概念

二叉搜索树又称二叉排序树,它或者是一棵空树**,或者是具有以下性质的二叉树:

若它的左子树不为空,则左子树上所有节点的值都小于根节点的值

若它的右子树不为空,则右子树上所有节点的值都大于根节点的值

它的左右子树也分别为二叉搜索树

②操作-查找

二叉搜索树的查找类似于二分法查找

  1. public Node search(int key) {
  2. Node cur = root;
  3. while (cur != null) {
  4. if(cur.val == key) {
  5. return cur;
  6. }else if(cur.val < key) {
  7. cur = cur.right;
  8. }else {
  9. cur = cur.left;
  10. }
  11. }
  12. return null;
  13. }

③操作-插入

  1. public boolean insert(int key) {
  2. Node node = new Node(key);
  3. if(root == null) {
  4. root = node;
  5. return true;
  6. }
  7. Node cur = root;
  8. Node parent = null;
  9. while(cur != null) {
  10. if(cur.val == key) {
  11. return false;
  12. }else if(cur.val < key) {
  13. parent = cur;
  14. cur = cur.right;
  15. }else {
  16. parent = cur;
  17. cur = cur.left;
  18. }
  19. }
  20. //parent
  21. if(parent.val > key) {
  22. parent.left = node;
  23. }else {
  24. parent.right = node;
  25. }
  26. return true;
  27. }

④操作-删除

删除操作较为复杂,但理解了其原理还是比较容易

设待删除结点为 cur, 待删除结点的双亲结点为 parent

1. cur.left == null

  1. cur 是 root,则 root = cur.right

  2. cur 不是 root,cur 是 parent.left,则 parent.left = cur.right

  3. cur 不是 root,cur 是 parent.right,则 parent.right = cur.right

2. cur.right == null

  1. cur 是 root,则 root = cur.left

  2. cur 不是 root,cur 是 parent.left,则 parent.left = cur.left

  3. cur 不是 root,cur 是 parent.right,则 parent.right = cur.left

第二种情况和第一种情况相同,只是方向相反,这里不再画图

3. cur.left != null && cur.right != null

需要使用替换法进行删除,即在它的右子树中寻找中序下的第一个结点(关键码最小),用它的值填补到被删除节点中,再来处理该结点的删除问题

当我们在左右子树都不为空的情况下进行删除,删除该节点会破坏树的结构,因此用替罪羊的方法来解决,实际删除的过程还是上面的两种情况,这里还是用到了搜索二叉树的性质

  1. public void remove(Node parent,Node cur) {
  2. if(cur.left == null) {
  3. if(cur == root) {
  4. root = cur.right;
  5. }else if(cur == parent.left) {
  6. parent.left = cur.right;
  7. }else {
  8. parent.right = cur.right;
  9. }
  10. }else if(cur.right == null) {
  11. if(cur == root) {
  12. root = cur.left;
  13. }else if(cur == parent.left) {
  14. parent.left = cur.left;
  15. }else {
  16. parent.right = cur.left;
  17. }
  18. }else {
  19. Node targetParent = cur;
  20. Node target = cur.right;
  21. while (target.left != null) {
  22. targetParent = target;
  23. target = target.left;
  24. }
  25. cur.val = target.val;
  26. if(target == targetParent.left) {
  27. targetParent.left = target.right;
  28. }else {
  29. targetParent.right = target.right;
  30. }
  31. }
  32. }
  33. public void removeKey(int key) {
  34. if(root == null) {
  35. return;
  36. }
  37. Node cur = root;
  38. Node parent = null;
  39. while (cur != null) {
  40. if(cur.val == key) {
  41. remove(parent,cur);
  42. return;
  43. }else if(cur.val < key){
  44. parent = cur;
  45. cur = cur.right;
  46. }else {
  47. parent = cur;
  48. cur = cur.left;
  49. }
  50. }
  51. }

⑤性能分析

插入和删除操作都必须先查找,查找效率代表了二叉搜索树中各个操作的性能。

对有n个结点的二叉搜索树,若每个元素查找的概率相等,则二叉搜索树平均查找长度是结点在二叉搜索树的深度 的函数,即结点越深,则比较次数越多。

但对于同一个关键码集合,如果各关键码插入的次序不同,可能得到不同结构的二叉搜索树

最优情况下,二叉搜索树为完全二叉树,其平均比较次数为:

最差情况下,二叉搜索树退化为单支树,其平均比较次数为:

4,笔试习题

①二叉树前序遍历

  1. void preOrderTraversal(TreeNode root){
  2. if(root == null) {
  3. return;
  4. }
  5. System.out.print(root.val+" ");
  6. preOrderTraversal(root.left);
  7. preOrderTraversal(root.right);
  8. }

②二叉树中序遍历

  1. void inOrderTraversal(TreeNode root){
  2. if(root == null) {
  3. return;
  4. }
  5. inOrderTraversal(root.left);
  6. System.out.print(root.val+" ");
  7. inOrderTraversal(root.right);
  8. }

③二叉树后序遍历

  1. void postOrderTraversal(TreeNode root){
  2. if(root == null) {
  3. return;
  4. }
  5. postOrderTraversal(root.left);
  6. postOrderTraversal(root.right);
  7. System.out.print(root.val+" ");
  8. }

④检查两棵树是否相同

  1. public boolean isSameTree(TreeNode p,TreeNode q){
  2. if(p == null && q != null){
  3. return false;
  4. }
  5. if(p != null && q == null){
  6. return false;
  7. }
  8. if(p == null && q ==null){
  9. return true;
  10. }
  11. if(p.val != q.val){
  12. return false;
  13. }
  14. return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
  15. }

⑤二叉树的最大深度

  1. public int maxDepth(TreeNode root){
  2. if(root == null){
  3. return 0;
  4. }
  5. int leftHeight = maxDepth(root.left);
  6. int rightHeight = maxDepth(root.right);
  7. return Math.abs(leftHeight-rightHeight > 0? leftHeight + 1: rightHeight + 1);
  8. }

⑥另一颗树的子树

  1. public boolean isSameTree(TreeNode p,TreeNode q){
  2. if(p == null && q != null){
  3. return false;
  4. }
  5. if(p != null && q == null){
  6. return false;
  7. }
  8. if(p == null && q ==null){
  9. return true;
  10. }
  11. if(p.val != q.val){
  12. return false;
  13. }
  14. return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
  15. }
  16. public boolean isSubtree(TreeNode root, TreeNode suBroot){
  17. if(root == null && suBroot == null){
  18. return true;
  19. }
  20. if(isSameTree(root,suBroot)){
  21. return true;
  22. }
  23. if(isSubtree(root.right,suBroot)){
  24. return true;
  25. }
  26. if(isSubtree(root.left,suBroot)){
  27. return true;
  28. }
  29. return false;
  30. }

⑦判断一颗树是否为一颗平衡二叉树

  1. public int maxDepth(TreeNode root){
  2. if(root == null){
  3. return 0;
  4. }
  5. int leftHeight = maxDepth(root.left);
  6. int rightHeight = maxDepth(root.right);
  7. return Math.abs(leftHeight-rightHeight > 0? leftHeight + 1: rightHeight + 1);
  8. }
  9. public boolean isBalanced(TreeNode root) {
  10. if(root == null) {
  11. return true;
  12. }
  13. int leftHeight = maxDepth(root.left);
  14. int rightHeight = maxDepth(root.right);
  15. return
  16. Math.abs(leftHeight-rightHeight) < 2 && isBalanced(root.left) && isBalanced(root.right);
  17. }

  1. public int hight(TreeNode root){
  2. if(root == null){
  3. return 0;
  4. }
  5. int leftHeight = hight(root.left);
  6. int rightHeight = hight(root.right);
  7. if(leftHeight >= 0 && rightHeight >= 0 && Math.abs(leftHeight-rightHeight) <= 1){
  8. return Math.max(leftHeight,rightHeight)+1;
  9. }else{
  10. return -1;
  11. }
  12. }
  13. public boolean isBalanced2(TreeNode root) {
  14. return hight(root) >= 0;
  15. }

⑧对称二叉树

  1. public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
  2. if(leftTree != null && rightTree == null){
  3. return false;
  4. }
  5. if(leftTree == null && rightTree != null){
  6. return false;
  7. }
  8. if(leftTree == null && rightTree == null){
  9. return true;
  10. }
  11. if(leftTree.val != rightTree.val){
  12. return false;
  13. }
  14. return isSymmetricChild(leftTree.left,rightTree.right) &&
  15. isSymmetricChild(leftTree.left,rightTree.right);
  16. }
  17. public boolean isSymmetric(TreeNode root){
  18. if(root == null){
  19. return true;
  20. }
  21. return isSymmetricChild(root.left,root.right);
  22. }

⑨二叉树镜像

  1. public TreeNode Mirror(TreeNode pRoot){
  2. if(pRoot == null){
  3. return pRoot;
  4. }
  5. if(pRoot.left == null && pRoot.right == null){
  6. return pRoot;
  7. }
  8. TreeNode tmp = pRoot.left;
  9. pRoot.left = pRoot.right;
  10. pRoot.right = tmp;
  11. if(pRoot.left != null){
  12. Mirror(pRoot.left);
  13. return pRoot;
  14. }
  15. if(pRoot.right != null){
  16. Mirror(pRoot.right);
  17. return pRoot;
  18. }
  19. return pRoot;
  20. }

五,优先级队列(堆)

1,二叉树的顺序存储

①存储方式

使用数组保存二叉树结构,方式即将二叉树用层序遍历方式放入数组中。 一般只适合表示完全二叉树,因为非完全二叉树会有空间的浪费。 这种方式的主要用法就是堆的表示。

②下标关系

已知双亲(parent)的下标,则:

左孩子(left)下标 = 2 * parent + 1;

右孩子(right)下标 = 2 * parent + 2;

已知孩子(不区分左右)(child)下标,则:

双亲(parent)下标 = (child - 1) / 2;

③二叉树顺序遍历

  1. // 层序遍历
  2. void levelOrderTraversal(TreeNode root) {
  3. if(root == null) {
  4. return;
  5. }
  6. Queue<TreeNode> queue = new LinkedList<>();
  7. queue.offer(root);
  8. while (!queue.isEmpty()) {
  9. TreeNode top = queue.poll();
  10. System.out.print(top.val+" ");
  11. if(top.left != null) {
  12. queue.offer(top.left);
  13. }
  14. if(top.right!=null) {
  15. queue.offer(top.right);
  16. }
  17. }
  18. System.out.println();
  19. }

2,堆

①概念

  1. 堆逻辑上是一棵完全二叉树

  2. 堆物理上是保存在数组中

  3. 满足任意结点的值都大于其子树中结点的值,叫做大堆,或者大根堆,或者最大堆

  4. 反之,则是小堆,或者小根堆,或者最小堆

②操作-向下调整

前提:

左右子树必须已经是一个堆,才能调整。

说明:

  1. array 代表存储堆的数组

  2. size 代表数组中被视为堆数据的个数

  3. index 代表要调整位置的下标

  4. left 代表 index 左孩子下标

  5. right 代表 index 右孩子下标

  6. min 代表 index 的最小值孩子的下标

过程(以小堆为例):

Ⅰ index 如果已经是叶子结点,则整个调整过程结束

  1. 判断 index 位置有没有孩子

  2. 因为堆是完全二叉树,没有左孩子就一定没有右孩子,所以判断是否有左孩子

  3. 因为堆的存储结构是数组,所以判断是否有左孩子即判断左孩子下标是否越界,即 left >= size 越界

Ⅱ 确定 left 或 right,谁是 index 的最小孩子 min

  1. 如果右孩子不存在,则 min = left

  2. 否则,比较 array[left] 和 array[right] 值得大小,选择小的为 min

Ⅲ比较 array[index] 的值 和 array[min] 的值,如果 array[index] <= array[min],则满足堆的性质,调整结束

Ⅳ否则,交换 array[index] 和 array[min] 的值

Ⅴ然后因为 min 位置的堆的性质可能被破坏,所以把 min 视作 index,向下重复以上过程

向下调整是以层序遍历的二叉树为例来遍历

  1. public void adjustDown(int root,int len){
  2. int parent = root;
  3. int child = 2*parent + 1;
  4. while(child < len){
  5. if (child + 1 < len && this.elem[child] < this.elem[child + 1] ){
  6. child++;
  7. }
  8. if(this.elem[child] > this.elem[parent]){
  9. int tmp = this.elem[parent];
  10. this.elem[parent] = this.elem[child];
  11. this.elem[child] = tmp;
  12. parent = child;
  13. child = 2*parent + 1;
  14. }else{
  15. break;
  16. }
  17. }
  18. }

③建堆(建大堆为例)

下面我们给出一个数组,这个数组逻辑上可以看做一颗完全二叉树,但是还不是一个堆,现在我们通过算法,把它构 建成一个堆。根节点左右子树不是堆,我们怎么调整呢?这里我们从倒数的第一个非叶子节点的子树开始调整,一直 调整到根节点的树,就可以调整成堆。

  1. //建大堆
  2. public void creatHeap(int[] array){
  3. for (int i = 0; i < array.length;i++){
  4. this.elem[i] = array[i];
  5. suedSize++;
  6. }
  7. for (int parent = (array.length - 1 - 1) / 2;parent >= 0;parent--){
  8. adjustDown(parent,this.suedSize);
  9. }

3,堆的应用-优先级队列

①概念

在很多应用中,我们通常需要按照优先级情况对待处理对象进行处理,比如首先处理优先级最高的对象,然后处理次 高的对象。最简单的一个例子就是,在手机上玩游戏的时候,如果有来电,那么系统应该优先处理打进来的电话。 在这种情况下,我们的数据结构应该提供两个最基本的操作,一个是返回最高优先级对象,一个是添加新的对象。这 种数据结构就是优先级队列(Priority Queue)

②内部原理

优先级队列的实现方式有很多,但最常见的是使用堆来构建。

③入队列

过程(以大堆为例):

  1. 首先按尾插方式放入数组

  2. 比较其和其双亲的值的大小,如果双亲的值大,则满足堆的性质,插入结束

  3. 否则,交换其和双亲位置的值,重新进行 2、3 步骤 4. 直到根结点

  1. public void adjustUp(int child){
  2. int parent = (child - 1) / 2;
  3. while(child>0){
  4. if(this.elem[child] > this.elem[parent]){
  5. int tmp = this.elem[parent];
  6. this.elem[parent] = this.elem[child];
  7. this.elem[child] = tmp;
  8. child = parent;
  9. parent = (child - 1) / 2;
  10. }else {
  11. break;
  12. }
  13. }
  14. }
  1. public void push(int val) {
  2. if (isFull()) {
  3. this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
  4. this.elem[this.suedSize] = val;
  5. this.suedSize++;
  6. adjustUp(this.suedSize - 1);
  7. }
  8. }

④出队列(优先级最高)

为了防止破坏堆的结构,删除时并不是直接将堆顶元素删除,而是用数组的最后一个元素替换堆顶元素,然后通过向下调整方式重新调整成堆

  1. public boolean isEmpty(){
  2. return this.suedSize == 0;
  3. }
  1. public void pop(){
  2. if(isEmpty()){
  3. return;
  4. }
  5. int tmp = this.elem[0];
  6. this.elem[0] = this.elem[this.suedSize-1];
  7. this.elem[this.suedSize-1] = tmp;
  8. this.suedSize--;
  9. adjustDown(0,this.suedSize);
  10. }

⑤返回队首元素(优先级最高)

  1. public int peek(){
  2. if(isEmpty()){
  3. return -1;
  4. }
  5. return this.elem[0];
  6. }
  1. public boolean isFull(){
  2. return this.suedSize == this.elem.length;
  3. }

4,堆排序

  1. /**
  2. * 一定是先创建大堆
  3. * 调整每棵树
  4. * 开始堆排序:
  5. * 先交换 后调整 直到 0下标
  6. */
  7. public void heapSort(){
  8. int end = this.suedSize-1;
  9. while (end > 0){
  10. int tmp = this.elem[0];
  11. this.elem[0] = this.elem[end];
  12. this.elem[end] = tmp;
  13. adjustDown(0,end);
  14. end--;
  15. }
  16. }

六,排序

1,概念

①排序

排序,就是使一串记录,按照其中的某个或某些关键字的大小,递增或递减的排列起来的操作。 平时的上下文中,如果提到排序,通常指的是排升序(非降序)。 通常意义上的排序,都是指的原地排序(in place sort)。

②稳定性

两个相等的数据,如果经过排序后,排序算法能保证其相对位置不发生变化,则我们称该算法是具备稳定性的排序算法

或者我们说没有跳跃的排序也是稳定的排序

2,排序详解

①直接插入排序

整个区间被分为

  1. 1. 有序区间
  2. 2. 无序区间

每次选择无序区间的第一个元素,在有序区间内选择合适的位置插入

  1. public static void main(String[] args) {
  2. int[] array = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,77};
  3. insertSort(array);
  4. System.out.println(Arrays.toString(array));
  5. }
  1. /**
  2. * 时间复杂度:
  3. * 最好:O(N) -> 数据是有序的
  4. * 最坏:O(N^2) -> 无序的数据
  5. * 空间复杂度:O(1)
  6. * 稳定性:稳定排序
  7. * @param array
  8. */
  9. public static void insertSort(int[] array) {
  10. for(int i = 1;i < array.length;i++) {//n-1
  11. int tmp = array[i];
  12. int j = i-1;
  13. for(; j >= 0;j--) {//n-1
  14. if(array[j] > tmp) {
  15. array[j+1] = array[j];
  16. }else{
  17. //array[j+1] = tmp;
  18. break;
  19. }
  20. }
  21. array[j+1] = tmp;
  22. }
  23. }

②希尔排序

希尔排序法又称缩小增量法。希尔排序法的基本思想是:先选定一个整数,把待排序文件中所有记录分成个组,所有 距离为的记录分在同一组内,并对每一组内的记录进行排序。然后,取,重复上述分组和排序的工作。当到达=1时, 所有记录在统一组内排好序。

  1. 希尔排序是对直接插入排序的优化。

  2. 当gap > 1时都是预排序,目的是让数组更接近于有序。当gap == 1时,数组已经接近有序的了,这样就会很 快。这样整体而言,可以达到优化的效果。我们实现后可以进行性能测试的对比。

  1. /**
  2. * 时间复杂度:不好算 n^1.3 - n^1.5 之间
  3. * 空间复杂度:O(1)
  4. * 稳定性:不稳定的排序
  5. * 技巧:如果在比较的过程当中 没有发生跳跃式的交换 那么就是稳定的
  6. * @param array
  7. *
  8. *
  9. * @param array 排序的数组
  10. * @param gap 每组的间隔 -》 组数
  11. */
  12. public static void shell(int[] array,int gap) {
  13. for (int i = gap; i < array.length; i++) {
  14. int tmp = array[i];
  15. int j = i-gap;
  16. for (; j >= 0; j -= gap) {
  17. if(array[j] > tmp) {
  18. array[j+gap] = array[j];
  19. }else {
  20. break;
  21. }
  22. }
  23. array[j+gap] = tmp;
  24. }
  25. }
  1. public static void main(String[] args) {
  2. int[] array = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,77};
  3. shell(array,5);
  4. System.out.println(Arrays.toString(array));
  5. }

③直接选择排序

每一次从无序区间选出最大(或最小)的一个元素,存放在无序区间的最后(或最前),直到全部待排序的数据元素排完 。

  1. public static void main(String[] args) {
  2. int[] array = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,77};
  3. selectSort(array);
  4. System.out.println(Arrays.toString(array));
  5. }
  1. /**
  2. * 时间复杂度:
  3. * 最好:O(N^2)
  4. * 最坏:O(N^2)
  5. * 空间复杂度:O(1)
  6. * 稳定性:不稳定的
  7. * @param array
  8. */
  9. public static void selectSort(int[] array) {
  10. for (int i = 0; i < array.length; i++) {
  11. for (int j = i+1; j < array.length; j++) {
  12. if(array[j] < array[i]) {
  13. int tmp = array[i];
  14. array[i] = array[j];
  15. array[j] = tmp;
  16. }
  17. }
  18. }
  19. }

④堆排序

基本原理也是选择排序,只是不在使用遍历的方式查找无序区间的最大的数,而是通过堆来选择无序区间的最大的数。

注意: 排升序要建大堆;排降序要建小堆。

  1. public static void main(String[] args) {
  2. int[] array = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,77};
  3. heapSort(array);
  4. System.out.println(Arrays.toString(array));
  5. }
  1. public static void siftDown(int[] array,int root,int len) {
  2. int parent = root;
  3. int child = 2*parent+1;
  4. while (child < len) {
  5. if(child+1 < len && array[child] < array[child+1]) {
  6. child++;
  7. }
  8. //child的下标就是左右孩子的最大值下标
  9. if(array[child] > array[parent]) {
  10. int tmp = array[child];
  11. array[child] = array[parent];
  12. array[parent] = tmp;
  13. parent = child;
  14. child = 2*parent+1;
  15. }else {
  16. break;
  17. }
  18. }
  19. }
  20. public static void createHeap(int[] array) {
  21. //从小到大排序 -》 大根堆
  22. for (int i = (array.length-1 - 1) / 2; i >= 0 ; i--) {
  23. siftDown(array,i,array.length);
  24. }
  25. }
  26. /**
  27. * 时间复杂度:O(N*logN) 都是这个时间复杂度
  28. * 复杂度:O(1)
  29. * 稳定性:不稳定的排序
  30. * @param array
  31. */
  32. public static void heapSort(int[] array) {
  33. createHeap(array);//O(n)
  34. int end = array.length-1;
  35. while (end > 0) {//O(N*logN)
  36. int tmp = array[end];
  37. array[end] = array[0];
  38. array[0] = tmp;
  39. siftDown(array,0,end);
  40. end--;
  41. }
  42. }

冒泡排序

在无序区间,通过相邻数的比较,将最大的数冒泡到无序区间的最后,持续这个过程,直到数组整体有序

  1. public static void main(String[] args) {
  2. int[] array = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,77};
  3. bubbleSort(array);
  4. System.out.println(Arrays.toString(array));
  5. }
  1. /**
  2. * 时间复杂度:
  3. * 最好最坏都是O(n^2)
  4. * 空间复杂度:O(1)
  5. * 稳定性:稳定的排序
  6. * 冒泡 直接插入
  7. * @param array
  8. */
  9. public static void bubbleSort(int[] array) {
  10. for (int i = 0; i < array.length-1; i++) {
  11. for (int j = 0; j < array.length-1-i; j++) {
  12. if(array[j] > array[j+1]) {
  13. int tmp = array[j];
  14. array[j] = array[j+1];
  15. array[j+1] = tmp;
  16. }
  17. }
  18. }
  19. }

快速排序

  1. 从待排序区间选择一个数,作为基准值(pivot);

  2. Partition: 遍历整个待排序区间,将比基准值小的(可以包含相等的)放到基准值的左边,将比基准值大的(可 以包含相等的)放到基准值的右边;

  3. 采用分治思想,对左右两个小区间按照同样的方式处理,直到小区间的长度 == 1,代表已经有序,或者小区间 的长度 == 0,代表没有数据

  1. public static void main(String[] args) {
  2. int[] array = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,77};
  3. quickSort1(array);
  4. System.out.println(Arrays.toString(array));
  5. }
  1. public static int partition(int[] array,int low,int high) {
  2. int tmp = array[low];
  3. while (low < high) {
  4. while (low < high && array[high] >= tmp) {
  5. high--;
  6. }
  7. array[low] = array[high];
  8. while (low < high && array[low] <= tmp) {
  9. low++;
  10. }
  11. array[high] = array[low];
  12. }
  13. array[low] = tmp;
  14. return low;
  15. }
  16. public static void quick(int[] array,int start,int end) {
  17. if(start >= end) {
  18. return;
  19. }
  20. int mid = (start+end)/2;
  21. int pivot = partition(array,start,end);
  22. quick(array,start,pivot-1);
  23. quick(array,pivot+1,end);
  24. }
  25. /**
  26. * 时间复杂度:
  27. * 最好:O(n*logn) 均匀的分割下
  28. * 最坏:o(n^2) 数据有序的时候
  29. * 空间复杂度:
  30. * 最好:logn
  31. * 最坏:O(n)
  32. * 稳定性:不稳定的排序
  33. *
  34. * k*n*logn
  35. * 2
  36. * 1.2
  37. * @param array
  38. */
  39. public static void quickSort1(int[] array) {
  40. quick(array,0,array.length-1);
  41. }

⑦归并排序

归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子 序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。

  1. public static void main(String[] args) {
  2. int[] array = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,77};
  3. mergeSort1(array);
  4. System.out.println(Arrays.toString(array));
  5. }
  1. public static void merge(int[] array,int low,int mid,int high) {
  2. int s1 = low;
  3. int e1 = mid;
  4. int s2 = mid+1;
  5. int e2 = high;
  6. int[] tmp = new int[high-low+1];
  7. int k = 0;//代表tmp数组的下标
  8. while (s1 <= e1 && s2 <= e2) {
  9. if(array[s1] <= array[s2]) {
  10. tmp[k++] = array[s1++];
  11. }else {
  12. tmp[k++] = array[s2++];
  13. }
  14. }
  15. //有2种情况
  16. while (s1 <= e1){
  17. //说明第2个归并段没有了数据 把第1个归并段剩下的数据 全部拷贝过来
  18. tmp[k++] = array[s1++];
  19. }
  20. while (s2 <= e2) {
  21. //说明第1个归并段没有了数据 把第2个归并段剩下的数据 全部拷贝过来
  22. tmp[k++] = array[s2++];
  23. }
  24. //tmp数组当中 存储的就是当前归并好的数据
  25. for (int i = 0; i < tmp.length; i++) {
  26. array[i+low] = tmp[i];
  27. }
  28. }
  29. public static void mergeSortInternal(int[] array,int low,int high) {
  30. if(low >= high) {
  31. return;
  32. }
  33. int mid = (low+high) / 2;
  34. mergeSortInternal(array,low,mid);
  35. mergeSortInternal(array,mid+1,high);
  36. //合并的过程
  37. merge(array,low,mid,high);
  38. }
  39. /**
  40. * 时间复杂度: O(N*log n)
  41. * 空间复杂度:O(N)
  42. * 稳定性:稳定的
  43. * @param array
  44. */
  45. public static void mergeSort1(int[] array) {
  46. mergeSortInternal(array, 0,array.length-1);
  47. }


七,List

1,ArrayList简介

【说明】

  1. ArrayList实现了RandomAccess接口,表明ArrayList支持随机访问

  2. ArrayList实现了Cloneable接口,表明ArrayList是可以clone的

  3. ArrayList实现了Serializable接口,表明ArrayList是支持序列化的

  4. 和Vector不同,ArrayList不是线程安全的,在单线程下可以使用,在多线程中可以选择Vector或者 CopyOnWriteArrayList

  5. ArrayList底层是一段连续的空间,并且可以动态扩容,是一个动态类型的顺序表

  6. ArrayList使用

①ArrayList的构造

  1. public static void main(String[] args) {
  2. // ArrayList创建,推荐写法
  3. // 构造一个空的列表
  4. List<Integer> list1 = new ArrayList<>();
  5. // 构造一个具有10个容量的列表
  6. List<Integer> list2 = new ArrayList<>(10);
  7. list2.add(1);
  8. list2.add(2);
  9. list2.add(3);
  10. // list2.add("hello"); // 编译失败,List<Integer>已经限定了,list2中只能存储整形元素
  11. // list3构造好之后,与list中的元素一致
  12. ArrayList<Integer> list3 = new ArrayList<>(list2);
  13. // 避免省略类型,否则:任意类型的元素都可以存放,使用时将是一场灾难
  14. List list4 = new ArrayList();
  15. list4.add("111");
  16. list4.add(100);
  17. }

②ArrayList常见操作

  1. public static void main(String[] args) {
  2. ArrayList<String> list = new ArrayList<>();
  3. list.add("1234");
  4. list.add("zhongguo");
  5. list.add("aaaaa");
  6. list.add("gao");
  7. System.out.println(list);
  8. }

  1. //add源码
  2. public boolean add(E e) {
  3. ensureCapacityInternal(size + 1); // Increments modCount!!
  4. elementData[size++] = e;
  5. return true;
  6. }
  1. public static void main(String[] args) {
  2. ArrayList<String> list = new ArrayList<>();
  3. list.add("1234");
  4. list.add("zhongguo");
  5. list.add("aaaaa");
  6. list.add("gao");
  7. list.add(2,"ssss");
  8. System.out.println(list);
  9. }

  1. //add插入源码
  2. public void add(int index, E element) {
  3. rangeCheckForAdd(index);
  4. ensureCapacityInternal(size + 1); // Increments modCount!!
  5. System.arraycopy(elementData, index, elementData, index + 1,
  6. size - index);
  7. elementData[index] = element;
  8. size++;
  9. }
  1. public static void main(String[] args) {
  2. ArrayList<String> list = new ArrayList<>();
  3. list.add("1234");
  4. list.add("zhongguo");
  5. list.add("aaaaa");
  6. list.add("gao");
  7. ArrayList<String> list2 = new ArrayList<>();
  8. list2.add("111");
  9. list2.add("44554");
  10. list.addAll(list2);
  11. System.out.println(list);
  12. }

  1. //addAll源码
  2. public boolean addAll(Collection<? extends E> c) {
  3. Object[] a = c.toArray();
  4. int numNew = a.length;
  5. ensureCapacityInternal(size + numNew); // Increments modCount
  6. System.arraycopy(a, 0, elementData, size, numNew);
  7. size += numNew;
  8. return numNew != 0;
  9. }

  1. public static void main(String[] args) {
  2. ArrayList<String> list = new ArrayList<>();
  3. list.add("1234");
  4. list.add("zhongguo");
  5. list.add("aaaaa");
  6. list.add("gao");
  7. list.remove(2);
  8. System.out.println(list);
  9. }

  1. public static void main(String[] args) {
  2. ArrayList<String> list = new ArrayList<>();
  3. list.add("1234");
  4. list.add("zhongguo");
  5. list.add("aaaaa");
  6. list.add("gao");
  7. String a = list.get(1);
  8. System.out.println(a);
  9. System.out.println(list);
  10. }

③ ArrayList的遍历

  1. public static void main(String[] args) {
  2. ArrayList<String> list = new ArrayList<>();
  3. list.add("hello");
  4. list.add("123");
  5. list.add("jsss");
  6. System.out.println(list);
  7. System.out.println("===================");
  8. for (int i = 0; i < list.size(); i++) {
  9. System.out.print(list.get(i) + " ");
  10. }
  11. System.out.println();
  12. System.out.println("=====================");
  13. for (String s : list) {
  14. System.out.print(s + " ");
  15. }
  16. System.out.println();
  17. System.out.println("=========迭代器打印=======");
  18. Iterator<String> it = list.iterator();
  19. while (it.hasNext()){
  20. System.out.print(it.next() + " ");
  21. }
  22. System.out.println();
  23. System.out.println("==========迭代器list打印=======");
  24. ListIterator<String> it2 = list.listIterator();
  25. while (it2.hasNext()){
  26. System.out.print(it2.next() + " ");
  27. }
  28. }


八,Map和Set

1,搜索

①概念及场景

Map和set是一种专门用来进行搜索的容器或者数据结构,其搜索的效率与其具体的实例化子类有关。

搜索方式有:

  1. 直接遍历,时间复杂度为O(N),元素如果比较多效率会非常慢

  2. 二分查找,时间复杂度为 ,但搜索前必须要求序列是有序的 上述排序比较适合静态类型的查找,即一般不会对区间进行插入和删除操作了,而现实中的查找比如:

  3. 根据姓名查询考试成绩

  4. 通讯录,即根据姓名查询联系方式

  5. 不重复集合,即需要先搜索关键字是否已经在集合中

②模型

一般把搜索的数据称为关键字(Key),和关键字对应的称为值(Value),将其称之为Key-value的键值对,所以 模型会有两种:

  1. 纯 key 模型,比如:

有一个英文词典,快速查找一个单词是否在词典中 快速查找某个名字在不在通讯录中

  1. Key-Value 模型,比如:

统计文件中每个单词出现的次数,统计结果是每个单词都有与其对应的次数: 梁山好汉的江湖绰号:每个好汉都有自己的江湖绰号

2,Map的使用

①关于Map的说明

Map是一个接口类,该类没有继承自Collection,该类中存储的是结构的键值对,并且K一定是唯一的,不能重复。

②关于Map.Entry的说明

Map.Entry 是Map内部实现的用来存放键值对映射关系的内部类,该内部类中主要提供了 的获取,value的设置以及Key的比较方式。

方法解释K getKey()返回entry中key的值V getValue()返回entry中的valueV setValue(V value)将键值对中的value替换为指定value

③Map 的常用方法说明

  1. public static void main(String[] args) {
  2. Map<String,String> map = new HashMap<>();
  3. map.put("123","李白");
  4. map.put("124","杜甫");
  5. map.put("125","王昌龄");
  6. map.put("126", "文天祥");
  7. System.out.println(map);
  8. }

  1. public static void main(String[] args) {
  2. Map<String,String> map = new HashMap<>();
  3. map.put("123","李白");
  4. map.put("124","杜甫");
  5. map.put("125","王昌龄");
  6. map.put("126", "文天祥");
  7. String val = map.get("123");
  8. System.out.println(val);
  9. }
  1. public static void main(String[] args) {
  2. Map<String,String> map = new HashMap<>();
  3. map.put("123","李白");
  4. map.put("124","杜甫");
  5. map.put("125","王昌龄");
  6. map.put("126", "文天祥");
  7. String val;
  8. val = map.getOrDefault("123","李白");
  9. System.out.println(val);
  10. }

3,Set的使用

①常见方法说明

②TreeSet的使用案例

  1. public static void main(String[] args) {
  2. Set<String> set = new HashSet<>();
  3. set.add("123");
  4. set.add("124");
  5. set.add("125");
  6. System.out.println(set);
  7. }

  1. public static void main(String[] args) {
  2. Set<String> set = new HashSet<>();
  3. set.add("123");
  4. set.add("124");
  5. set.add("125");
  6. boolean fla = set.contains("123");
  7. System.out.println(fla);
  8. }

  1. public static void main(String[] args) {
  2. Set<String> set = new HashSet<>();
  3. set.add("123");
  4. set.add("124");
  5. set.add("125");
  6. Iterator<String> it = set.iterator();
  7. while (it.hasNext()){
  8. System.out.println(it.next());
  9. }
  10. }

标签: 数据结构

本文转载自: https://blog.csdn.net/qq_50156012/article/details/122099739
版权归原作者 /少司命 所有, 如有侵权,请联系我们删除。

“六万字数据结构基础知识大总结(含笔试面试习题)”的评论:

还没有评论