Java后端架构师的成长之路(一)——数据结构与算法(1)

数据结构与算法介绍

先看几个经典的算法面试题

字符串匹配问题

  • 有一个字符串 str1= ““硅硅谷 尚硅谷你尚硅 尚硅谷你尚硅谷你尚硅你好””,和一个子串 str2=“尚硅谷你尚硅你”;
  • 现在要判断 str1 是否含有 str2, 如果存在,就返回第一次出现的位置, 如果没有,则返回-1;
  • 要求用最快的速度来完成匹配;
  • 你的思路是什么?

思路一:暴力匹配
思路二:KMP算法《部分匹配表》

汉诺塔游戏

在这里插入图片描述

  • 将A塔的所有圆盘移动到C塔,规定:① 小圆盘上不能放大圆盘;② 在三根柱子之间一次只能移动一个圆盘。

使用分治算法

八皇后问题

  • 是一个古老而著名的问题,是回溯算法的典型案例。该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即:任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法
    在这里插入图片描述

  • 游戏演示:http://www.7k7k.com/swf/49842.htm

  • 使用到回溯算法。

  • 高斯认为有76种方案。1854年在柏林的象棋杂志上不同的作者发表了40种不同的解,后来有人用图论的方法解出92种结果。计算机发明后,有多种计算机语言可以解决此问题。

马踏棋盘

  • 马踏棋盘算法也被称为骑士周游问题;
  • 将马随机放在国际象棋的8×8棋盘,Board[0~7][0~7]的某个方格中,马按走棋规则(马走日字)进行移动。要求每个方格只进入一次,走遍棋盘上全部64个方格;
  • 游戏演示: http://www.4399.com/flash/146267_2.htm
    在这里插入图片描述
  • 会使用到图的深度优化遍历算法(DFS) + 贪心算法优化

数据结构和算法的重要性

  • 算法是程序的灵魂,优秀的程序可以在海量数据计算时,依然保持高速计算。
  • 一般来讲,程序会使用了内存计算框架(比如Spark)和缓存技术(比如Redis等)来优化程序,再深入的思考一下,这些计算框架和缓存技术,它的核心功能是哪个部分呢?
  • 拿实际工作经历来说, 在Unix下开发服务器程序,功能是要支持上千万人同时在线,在上线前,做内测一切OK,可上线后,服务器就支撑不住了,公司的CTO对代码进行优化,再次上线坚如磐石。你就能感受到程序是有灵魂的,就是算法。
  • 目前程序员面试的门槛越来越高,很多一线IT公司(大厂),都会有数据结构和算法面试题(负责的告诉你,肯定有的)。
  • 如果你不想永远都是代码工人,那就花时间来研究下数据结构和算法。

数据结构和算法的关系

  • 数据data结构(structure)是一门研究组织数据方式的学科,有了编程语言也就有了数据结构。学好数据结构可以编写出更加漂亮,更加有效率的代码。
  • 要学习好数据结构就要多多考虑如何将生活中遇到的问题,用程序去实现解决。
  • 程序 = 数据结构 + 算法。
  • 数据结构是算法的基础,换言之,想要学好算法,需要把数据结构学到位。

几个实际编程中遇到的问题

字符串替换

public static void main(String[] args) {
	String str = "Java,Java, hello,world!";
	String newStr = str.replaceAll("Java", "尚硅谷~"); //算法
	System.out.println("newStr=" + newStr);
}

Q:试写出用单链表表示的字符串类及字符串结点类的定义,并依次实现它的构造函数、以及计算串长度、串赋值、判断两串相等、求子串、两串连接、求子串在串中位置等7个成员函数。

五子棋程序

在这里插入图片描述

Q:如何判断游戏的输赢,并可以完成存盘退出和继续上局的功能。
棋盘 => 二维数组 => (稀疏数组) => 写入文件 【存档功能】
读取文件 => 稀疏数组 => 二维数组 => 棋盘 【接上局】

约瑟夫(Josephu)问题

  • 设编号为1,2,… n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m 的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,直到所有人出列为止,由此产生一个出队编号的序列。

用一个不带头结点的循环链表来处理Josephu 问题:先构成一个有n个结点的单循环链表(单向环形链表),然后由k结点起从1开始计数,计到m时,对应结点从链表中删除,然后再从被删除结点的下一个结点又从1开始计数,直到最后一个结点从链表中删除算法结束。

其它常见问题

  • 修路问题 => 最小生成树(加权值)【数据结构】+ 普利姆算法;
  • 最短路径问题 => 图+弗洛伊德算法;
  • 汉诺塔 => 分支算法;
  • 八皇后问题 => 回溯法。

线性结构和非线性结构

线性结构

  • 线性结构作为最常用的数据结构,其特点是数据元素之间存在一对一的线性关系。
  • 线性结构有两种不同的存储结构,即顺序存储结构和链式存储结构。顺序存储的线性表称为顺序表,顺序表中的存储元素是连续的。
  • 链式存储的线性表称为链表,链表中的存储元素不一定是连续的,元素节点中存放数据元素以及相邻元素的地址信息。
  • 线性结构常见的有:数组、队列、链表和栈。

非线性结构

  • 二维数组,多维数组,广义表,树结构,图结构。

稀疏数组和队列

稀疏数组SparseArray

  • 基本介绍:当一个数组中大部分元素为0,或者为同一个值时,可以使用稀疏数组来保存该数组。
  • 稀疏数组的处理方法是:记录数组一共有几行几列,有多少个不同的值;把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模。
  • 代码实现:
import java.io.*;

/**
 * 原始数组
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	1	0	0	0	0	0	0	0	0
 * 0	0	0	2	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	1	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * 0	0	0	0	0	0	0	0	0	0	0
 * <p>
 * 稀疏数组
 * 11	11	3
 * 1	2	1
 * 2	3	2
 * 4	5	1
 */
public class T01SparseArray {
    private static int[][] chessArr;
    private static final String FILENAME = "classpath:sparse.arr";

    public static void main(String[] args) throws IOException {
        // 1、初始化二维数组
        initOrgTwoDimArr();
        // 2、二维数组 转 稀疏数组
        int[][] sparseArr = twoDim2Sparse();
        // 3、稀疏数组写入文件
        writeArrToFile(sparseArr);
        // 4、将文件恢复成稀疏数组
        int[][] newSparseArr = readArrFromFile();
        // 5、稀疏数组 转 二维数组
        sparse2twoDim(newSparseArr);
    }

    /**
     * 1、初始化原始的二维数组
     */
    private static void initOrgTwoDimArr() {
        // 1、创建一个原始的二维数组 11 * 11
        // 0:表示没有值,1:黑子,2:蓝子
        chessArr = new int[11][11];
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;
        chessArr[4][5] = 1;

        System.out.println("原始的二维数组:");
        printTwoDimArr(chessArr);
    }

    /**
     * 2、二维数组 转 稀疏数组
     */
    private static int[][] twoDim2Sparse() {
        // 2、将二维数组 转为 稀疏数组
        // 2.1、遍历二维数组
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0) {
                    sum++;
                }
            }
        }
        // 2.2、创建对应的稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        // 给稀疏数组赋值
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        // 2.3、遍历二维数组,将非0的值放入到sparseArr
        // 定义 count 用于记录是第几个非0数据
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr[i][j];
                }
            }
        }

        System.out.println("得到的稀疏数组:");
        printTwoDimArr(sparseArr);
        return sparseArr;
    }

    /**
     * 3、将稀疏数组 写入 文件 sparse.arr
     */
    private static void writeArrToFile(int[][] sparseArr) throws IOException {
        Writer out = new FileWriter(new File(FILENAME));
        for (int i = 0; i < sparseArr.length; i++) {
            for (int j = 0; j < 3; j++) {
                out.write(sparseArr[i][j] + "\t");
            }
            out.write("\r\n");
        }
        System.out.println("保存文件成功");
        out.close();
    }

    /**
     * 4、将文件中的数据 恢复成 稀疏数组
     */
    private static int[][] readArrFromFile() throws IOException {
        FileReader fr = new FileReader(new File(FILENAME));
        BufferedReader br = new BufferedReader(fr);
        // 读取文件,看一下有多少行,以便初始化稀疏数组
        int line = 0;
        while (br.readLine() != null) {
            line++;
        }
        int[][] sparseArr = new int[line][3];

        // 再次读物每一行数据,拆分数据并给数组赋值
        fr = new FileReader(new File(FILENAME));
        br = new BufferedReader(fr);
        int count = 0;
        String s;
        while ((s = br.readLine()) != null) {
            String[] strArr = s.split("\t");
            sparseArr[count][0] = Integer.parseInt(strArr[0]);
            sparseArr[count][1] = Integer.parseInt(strArr[1]);
            sparseArr[count][2] = Integer.parseInt(strArr[2]);
            count++;
        }
        br.close();
        fr.close();
        System.out.println("从文件中恢复稀疏数组:");
        printTwoDimArr(sparseArr);
        return sparseArr;
    }

    /**
     * 5、稀疏数组 转 二维数组
     */
    private static void sparse2twoDim(int[][] sparseArr) {
        // 5、将稀疏数组 转为 原始的二维数组
        // 5.1、读取稀疏数组的第0行数据,创建原始的二维数组
        int[][] orgArr = new int[sparseArr[0][0]][sparseArr[0][1]];
        // 5.2、遍历稀疏数组的第后几行数据,并赋值给原始的二维数组
        for (int i = 1; i < sparseArr.length; i++) {
            orgArr[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        System.out.println("恢复得到二维数组:");
        printTwoDimArr(orgArr);
    }

    /**
     * 打印二维数组
     *
     * @param twoDimArr
     */
    private static void printTwoDimArr(int[][] twoDimArr) {
        for (int[] arr : twoDimArr) {
            for (int data : arr) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}

队列

队列的一个使用场景

  • 银行排队的案例
    在这里插入图片描述

队列的介绍

  • 队列是一个有序列表,可以用数组或是链表来实现。
  • 遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出。

数组模拟队列

思路
  • 队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图, 其中 maxSize 是该队列的最大容量。
    在这里插入图片描述
  • 因为队列的输出、输入是分别从前后端来处理,因此需要两个变量 front及 rear分别记录队列前后端的下标,front 会随着数据输出而改变,而 rear则是随着数据输入而改变。
  • 当我们将数据存入队列时称为”addQueue”,addQueue 的处理需要有两个步骤

将尾指针往后移:rear+1 , 当front == rear 【空】
若尾指针 rear 小于队列的最大下标 maxSize-1,则将数据存入 rear所指的数组元素中,否则无法存入数据。 rear == maxSize - 1[队列满]

代码实现
  • 定义一个队列接口:定义队列的相关操作
/**
 * 定义一个队列接口
 */
public interface Queue {
    /**
     * 判断队列是否满
     */
    boolean isFull();
    /**
     * 判断队列是否为空
     */
    boolean isEmpty();
    /**
     * 添加数据到队列
     */
    void addQueue(int n);
    /**
     * 获取队列的数据,出队列
     */
    int getQueue();
    /**
     * 打印队列的数据
     */
    void showQueue();
    /**
     * 显示队列的头数据,不是取数据
     */
    int headQueue();
}
  • 实现:
/**
 * 使用数组模拟一个队列,编写一个ArrayQueue
 */
class ArrayQueue implements Queue {
    /**
     * 数组最大容量
     */
    protected int maxSize;
    /**
     * 队列头
     */
    protected int front;
    /**
     * 队列尾
     */
    protected int rear;
    /**
     * 用于存放数据
     */
    protected int[] arr;
    /**
     * 创建队列的构造器
     */
    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        // 指向队列头部,队列头的前一个位置
        front = -1;
        // 指向队列尾,指向队列尾的数据
        rear = -1;
    }
    @Override
    public boolean isFull() {
        return rear == maxSize - 1;
    }
    @Override
    public boolean isEmpty() {
        return rear == front;
    }
    @Override
    public void addQueue(int n) {
        // 判断队列是否满
        if (isFull()) {
            throw new RuntimeException("队列满,不能加入数据");
        }
        rear++;
        arr[rear] = n;
    }
    @Override
    public int getQueue() {
        // 判断队列是否空
        if (isEmpty()) {
            // 抛异常
            throw new RuntimeException("队列空,不能取数据");
        }
        front++;
        return arr[front];
    }
    @Override
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列空,没有数据~");
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("arr[%d]=%d\n", i, arr[i]);
        }
    }
    @Override
    public int headQueue() {
        if (isEmpty()) {
            // 抛异常
            throw new RuntimeException("队列空,没有数据");
        }
        return arr[front + 1];
    }
}
测试
  • 定义一个测试App类
public class QueueApp {
    public static void play(Queue queue, String subject) {
        System.out.println(subject);
        // 菜单
        System.out.println("s(show):显示队列");
        System.out.println("e(exit):退出程序");
        System.out.println("a(add)[空格][number]:添加数据到队列");
        System.out.println("g(get):从队列获取数据");
        System.out.println("h(head):查看队列头的数据");

        // 接收用户输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop) {
            // 接收一个字符
            String command = scanner.nextLine().trim();
            char key = command.charAt(0);
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    int value = 0;
                    try {
                        value = Integer.parseInt(command.split(" ")[1]);
                        queue.addQueue(value);
                        System.out.printf("%d入队列成功!\n", value);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                        System.out.printf("%d入队列失败!\n", value);
                    }
                    break;
                case 'g':
                    try {
                        int res = queue.getQueue();
                        System.out.printf("取出的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = queue.headQueue();
                        System.out.printf("队列头的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出~~");
    }
}
  • 测试:
public class ArrayQueueDemo {
    public static void main(String[] args) {
        QueueApp.play(new ArrayQueue(3), "测试数组模拟队列的案例~~");
    }
}
  • 测试结果
测试数组模拟队列的案例~~
s(show):显示队列
e(exit):退出程序
a(add)[空格][number]:添加数据到队列
g(get):从队列获取数据
h(head):查看队列头的数据
s
队列空,没有数据~
a 10
10入队列成功!
a 20
20入队列成功!
a 30
30入队列成功!
a 40
队列满,不能加入数据
40入队列失败!
h
队列头的数据是10
g
取出的数据是10
h
队列头的数据是20
g
取出的数据是20
g
取出的数据是30
a 40
队列满,不能加入数据
40入队列失败!
e
程序退出~~
问题分析
  • 目前数组使用一次就不能用, 没有达到复用的效果
  • 将这个数组使用算法,改进成一个环形的队列取模:%

数组模拟环形队列

分析说明
  • 尾索引的下一个为头索引时表示队列满,即将队列容量空出一个作为约定,这个在做判断队列满的时候需要注意 (rear + 1) % maxSize == front [满]
  • rear == front [空]
思路
  • front变量的含义做一个调整:front就指向队列的第一个元素,也就是arr[front]是队列的第一个元素,front的初始值0;
  • rear遍历的含义做一个调整:rear指向队列的最后一个元素的后一个位置,因为希望空出一个空间作为约定,rear的初始值0;
  • 当队列满的时候,条件是 (rear + 1) % maxSize = front 【满】;
  • 当队列空的时候,rear == front;
  • 当我们这样分析,队列中有效的数据个数为:(rear + maxSize - front) % maxSize;
  • 我们就可以再原来的队列上修改得到一个环形队列
代码实现
class CircleArrayQueue extends ArrayQueue {
    /**
     * 创建队列的构造器
     */
    public CircleArrayQueue(int maxSize) {
        super(maxSize);
        front = 0;
        rear = 0;
    }

    @Override
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    @Override
    public void addQueue(int n) {
        // 判断队列是否满
        if (isFull()) {
            throw new RuntimeException("队列满,不能加入数据");
        }
        // 直接将数据加入
        arr[rear] = n;
        // 将rear后移,这里必须考虑后移
        rear = (rear + 1) % maxSize;
    }

    @Override
    public int getQueue() {
        // 判断队列是否空
        if (isEmpty()) {
            // 抛异常
            throw new RuntimeException("队列空,不能取数据");
        }
        // 这里需要分析出front是指向队列的第一个元素
        // 先把front对应的值保留到一个个临时的变量
        int value = arr[front];
        // 将front后移,并考虑取模
        front = (front + 1) % maxSize;
        // 将临时保存的变量返回
        return value;
    }

    @Override
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列空,没有数据~");
            return;
        }
        // 思路:从front开始遍历,遍历多少个元素
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    /**
     * 请当前队列的有些数据个数
     *
     * @return
     */
    private int size() {
        return (rear + maxSize - front) % maxSize;
    }

    @Override
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列空,没有数据");
        }
        return arr[front];
    }
}
测试
public class CircleArrayQueueDemo {
    public static void main(String[] args) {
        QueueApp.play(new CircleArrayQueue(4), "测试数据模拟环形队列的案例~~");
    }
}
  • 测试结果
测试数据模拟幻想队列的案例~~
s(show):显示队列
e(exit):退出程序
a(add)[空格][number]:添加数据到队列
g(get):从队列获取数据
h(head):查看队列头的数据
s
队列空,没有数据~
a 10
10入队列成功!
a 20
20入队列成功!
a 30
30入队列成功!
a 40
队列满,不能加入数据
40入队列失败!
h
队列头的数据是10
g
取出的数据是10
g
取出的数据是20
g
取出的数据是30
g
队列空,不能取数据
a 40
40入队列成功!
a 50
50入队列成功!
a 60
60入队列成功!
s
arr[3]=40
arr[0]=50
arr[1]=60
e
程序退出~~

链表

链表的介绍

  • 链表是有序的列表,但是它在内存中是存储如下:
    在这里插入图片描述
  • 链表是以节点的方式来存储,是链式存储。
  • 每个节点包含 data 域, next 域:指向下一个节点。
  • 而且链表的各个节点不一定是连续存储。
  • 链表分为:带头节点的链表和没有头节点的链表,根据实际的需求来确定。
  • 单链表(带头结点) 逻辑结构示意图如下:
    在这里插入图片描述

单向链表

应用实例

使用带头结点的单向链表实现,水浒英雄排行榜管理
1)完成对英雄人物的增删改查操作;
2)第一种方法在添加英雄时,直接添加到链表的尾部;
3)第二种方式在添加英雄时,根据排名将英雄插入到指定位置(如果有这个排名,则添加失败,并给出提示)

/**
 * 定义水浒英雄结点
 */
class HeroNode {
    public int no;
    public String name;
    public String nickname;
    public HeroNode next;

    public HeroNode(int no, String name, String nickname) {
        this.no = no;
        this.name = name;
        this.nickname = nickname;
    }

    // 为了显示方便,重写toString()方法
    @Override
    public String toString() {
        return "HeroNode[no=" + no + ", name=" + name + ", nickname=" + nickname + "]";
    }
}
/**
 * 对水浒英雄排行榜进行管理
 */
class SingleLinkedList {
    /**
     * 初始化头结点
     */
    private HeroNode head = new HeroNode(0, "", "");
    /**
     * 添加:当不考虑编号顺序时
     * 1、找到当前链表的最后一个结点
     * 2、将最后这个结点的next指向新的结点
     */
    public void add(HeroNode node) {
        // 因为 head 节点不能动,因此我们需要一个辅助遍历 temp
        HeroNode temp = head;
        // 遍历链表找到最后
        while (temp.next != null) {
            temp = temp.next;
        }
        // 当退出 while 循环时,temp 就指向了链表的最后,将最后这个节点的 next 指向 新的节点
        temp.next = node;
    }
    /**
     * 有序添加:根据排名将英雄插入到指定位置
     * 如果有这个排名,则添加失败,并给出提示
     */
    public void addByOrder(HeroNode node) {
        HeroNode temp = head;

        while (temp.next != null) {
            if (temp.next.no > node.no) {
                // 位置找到,就在 temp 的后面插入
                node.next = temp.next;
                temp.next = node;
                break;
            } else if (temp.next.no == node.no) {
                System.out.printf("准备插入的英雄的编号 %d 已经存在了, 不能加入\n", node.no);
                return;
            }
            temp = temp.next;
        }

        if (temp.next == null) {
            temp.next = node;
        }
    }
    /**
     * 修改结点的信息:根据 no 编号来修改,即 no 编号不能改
     */
    public void updateByNo(HeroNode node) {
        // 判断链表是否为空
        if (head.next == null) {
            System.out.println("链表为空");
            return;
        }
        // 找到需要修改的节点, 根据 no 编号
        // 定义一个辅助变量
        HeroNode temp = head.next;
        while (temp != null) {
            if (temp.no == node.no) {
                // 找到
                temp.name = node.name;
                temp.nickname = node.nickname;
                return;
            }
            temp = temp.next;
        }

        System.out.printf("没有找到 编号 %d 的节点,不能修改\n", node.no);
    }
    /**
     * 删除结点
     * 思路:head 不能动,因此我们需要一个 temp 辅助节点找到待删除节点的前一个节点
     * 说明我们在比较时,是 temp.next.no 和 需要删除的节点的 no 比较
     */
    public void deleteByNo(int no) {
        HeroNode temp = head;
        while (temp.next != null) {
            if (temp.next.no == no) {
                // 找到了待删除节点的前一个节点 temp
                temp.next = temp.next.next;
                return;
            }
            temp = temp.next;
        }
        System.out.printf("要删除的 %d 节点不存在\n", no);
    }
    /**
     * 打印链表
     */
    public void print() {
        // 判断链表是否为空
        if (head.next == null) {
            System.out.println("链表为空");
            return;
        }
        HeroNode temp = head;
        while (temp.next != null) {
            System.out.println(temp.next);
            temp = temp.next;
        }
    }
}
  • 测试
public class SingleLinkedListDemo {
    public static void main(String[] args) {
        SingleLinkedList linkedList = new SingleLinkedList();
//        // 1、创建链表
//        linkedList.add(new HeroNode(1, "宋江", "及时雨"));
//        linkedList.add(new HeroNode(2, "卢俊义", "玉麒麟"));
//        linkedList.add(new HeroNode(3, "吴用", "智多星"));
//        linkedList.add(new HeroNode(4, "林冲", "豹子头"));
//        linkedList.print();
        // 2、按编号顺序创建链表
        linkedList.addByOrder(new HeroNode(1, "宋江", "及时雨"));
        linkedList.addByOrder(new HeroNode(3, "吴用", "智多星"));
        linkedList.addByOrder(new HeroNode(2, "卢俊义", "玉麒麟"));
        linkedList.addByOrder(new HeroNode(4, "林冲", "豹子头"));
        linkedList.addByOrder(new HeroNode(4, "林冲", "豹子头"));
        linkedList.print();
        // 3、修改结点
        linkedList.updateByNo(new HeroNode(2, "小卢", "麒麟~~"));
        System.out.println("修改后的链表情况:");
        linkedList.print();
        // 4、删除结点
        linkedList.deleteByNo(1);
//        linkedList.deleteByNo(2);
//        linkedList.deleteByNo(3);
        linkedList.deleteByNo(4);
        System.out.println("修改后的链表情况:");
        linkedList.print();
    }
}
  • 结果输出:
准备插入的英雄的编号 4 已经存在了, 不能加入
HeroNode[no=1, name=宋江, nickname=及时雨]
HeroNode[no=2, name=卢俊义, nickname=玉麒麟]
HeroNode[no=3, name=吴用, nickname=智多星]
HeroNode[no=4, name=林冲, nickname=豹子头]
修改后的链表情况:
HeroNode[no=1, name=宋江, nickname=及时雨]
HeroNode[no=2, name=小卢, nickname=麒麟~~]
HeroNode[no=3, name=吴用, nickname=智多星]
HeroNode[no=4, name=林冲, nickname=豹子头]
修改后的链表情况:
HeroNode[no=2, name=小卢, nickname=麒麟~~]
HeroNode[no=3, name=吴用, nickname=智多星]

面试题

  • 准备工作:单向链表、创建、打印
public class LinkedListTest {
    static class LinkedNode {
        private int value;
        private LinkedNode next;

        public LinkedNode(int value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "LinkedNode[value=" + value + "]";
        }
    }

    public static void main(String[] args) {
        // 1、创建一个不带头节点的单向链表
        LinkedNode head = createLinkedList(5, 4, 1, 3, 8, 9, 7);
        System.out.print("① 单向链表:");
        printLinkedList(head);
        // 2、求单链表中有效节点的个数
        System.out.println("② 单向链表中有效结点个数:" + getLength(head));
        // 3、查找单链表中的倒数第k个结点
        System.out.printf("③ 单链表中倒数第%d个结点:%s\n", 4, findLastIndexNode(head, 4));
        // 4、单链表的反转
        reverseLinkedList(head);
        System.out.print("④ 反转后的链表:");
        printLinkedList(head);
        // 5、逆序打印链表
        System.out.print("⑤ 逆序打印链表:");
        reversePrint(head);
        // 6、合并两个有序链表
        System.out.print("⑥ 合并两个有序链表:");
        LinkedNode head1 = createLinkedList(1, 3, 5, 7);
        LinkedNode head2 = createLinkedList(2, 4, 6, 8, 10);
        LinkedNode newHead = margeTwoLinkedList(head1, head2);
        printLinkedList(newHead);
    }
    /**
     * 根据传入的值,创建一个单向链表
     * @param values 一组整数
     * @return 单向链表头结点
     */
    private static LinkedNode createLinkedList(int... values) {
        LinkedNode head = null, cursor = null;
        for (int value : values) {
            LinkedNode node = new LinkedNode(value);
            if (cursor == null) {
                head = node;
            } else {
                cursor.next = node;
            }
            cursor = node;
        }
        return head;
    }
    /**
     * 打印链表
     */
    private static void printLinkedList(LinkedNode head) {
        LinkedNode cursor = head;
        while (cursor != null) {
            System.out.printf("%d -> ", cursor.value);
            cursor = cursor.next;
        }
        System.out.println("null");
    }
}
// 单向链表:5 -> 4 -> 1 -> 3 -> 8 -> 9 -> 7 -> null
求单链表中有效结点的个数
	/**
     * 求单链表中有效节点的个数
     */
    private static int getLength(LinkedNode head) {
        int length = 0;
        LinkedNode cursor = head;
        while (cursor != null) {
            length++;
            cursor = cursor.next;
        }
        return length;
    }
查找单链表中的倒数第k个结点

-【新浪面试题】

	/**
     * 查找单链表中的倒数第k个结点
     */
    private static LinkedNode findLastIndexNode(LinkedNode head, int index) {
        // 第一次遍历,得到链表的长度
        int length = getLength(head);
        if (length <= 0 || index > length) {
            return null;
        }
        // 第二次遍历,for循环定位到 倒数的index
        LinkedNode cursor = head;
        for (int i = 0;i <length - index;i++) {
            cursor = cursor.next;
        }
        return cursor;
    }
单链表的反转

-【腾讯面试题,有点难度】

	/**
     * 单链表的反转
     * 注:不带头结点,head 引用传递,所以先反转head.next之后的结点
     */
    private static void reverseLinkedList(LinkedNode head) {
        if (head == null || head.next == null) {
            return;
        }
        // 定义一个游标,用于遍历链表,从head的下一个结点开始
        LinkedNode cursor = head.next;
        // 定义一个辅助变量,初始值为原始的头结点的值
        LinkedNode tempHead = new LinkedNode(head.value);
        // 指向当前结点[cursor]的下一个结点
        LinkedNode next;
        while (cursor != null) {
            // 先暂存一下cursor的下一个结点
            next = cursor.next;

            // 摘下(取下)cursor结点,并指向新的链表的最前端
            cursor.next = tempHead;
            tempHead = cursor;

            // cursor 后移
            cursor = next;
        }
        // 将head指向tempHead,实现单链表反转
        head.value = tempHead.value;
        head.next = tempHead.next;
    }
从尾到头打印单链表

-【百度面试题,方法1:反向遍历 。 方法2:利用Stack栈】

	/**
     * 从尾到头打印单链表
     * 可以利用栈这个数据结构,将各个节点压入到栈中,然后利用栈的先进后出的特点
     * 就实现了逆序打印的效果
     */
    private static void reversePrint(LinkedNode head) {
        if (head == null) {
            // 空链表
            System.out.println("null");
            return;
        }
        // 创建一个栈,将各个结点压入栈
        Stack<LinkedNode> stack = new Stack<>();
        // 创建一个游标,用于遍历
        LinkedNode cursor = head;
        while (cursor != null) {
            stack.push(cursor);
            cursor = cursor.next;
        }
        // pop出栈,打印栈中的节点
        while (stack.size() > 0) {
            System.out.printf("%d -> ", stack.pop().value);
        }
        System.out.println("null");
    }
合并两个有序的单链表,合并之后的链表依然有序
	/**
     * 合并两个有序的单链表,合并之后的链表依然有序
     */
    private static LinkedNode margeTwoLinkedList(LinkedNode head1, LinkedNode head2) {
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        // 经过上面的边界值判断,head1 != null,head2 != null

        // 合并后的链表表头,设置为head1、head2中最小的那一个
        LinkedNode head = head1.value < head2.value ? head1 : head2;
        // 定义两个个游标指针
        LinkedNode cursor1 = head == head1 ? head1 : head2;
        LinkedNode cursor2 = head == head1 ? head2 : head1;
        LinkedNode pre = cursor1;
        LinkedNode next;
        // 遍历
        while (cursor1 != null && cursor2 != null) {
            int value1 = cursor1.value;
            int value2 = cursor2.value;
            if (value1 <= value2) {
                pre = cursor1;
                cursor1 = cursor1.next;
            } else {
                next = cursor2.next;
                pre.next = cursor2;
                cursor2.next = cursor1;
                pre = cursor2;
                cursor2 = next;
            }
        }
        pre.next = cursor1 == null ? cursor2 : cursor1;

        return head;
    }
两个链表生成相加链表
/**
 * 两个链表生成相加链表
 * 假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
 * 给定两个这种链表,请生成代表两个整数相加值的结果链表。
 * 例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
 * 输入描述
 * 第一行两个整数 n 和 m,分别表示两个链表的长度。
 * <p>
 * 第二行 n 个整数 ai 表示第一个链表的节点。
 * <p>
 * 第三行 m 个整数 bi 表示第二个链表的节点。
 * 输出描述
 * 输出一行整数表示结果链表。
 * 示例1
 * 输入
 * 3 2
 * 9 3 7
 * 6 3
 * 输出
 * 1 0 0 0
 * <p>
 * 测试用例1:
 * 40 40
 * 5 9 7 5 7 1 2 6 4 2 7 8 9 6 1 6 6 1 1 4 2 9 5 5 0 4 6 3 0 4 3 5 6 7 0 5 5 4 4 0
 * 1 3 2 5 0 6 0 2 1 4 3 9 3 0 9 9 0 3 1 6 5 7 8 6 2 3 8 5 0 9 7 9 4 5 9 9 4 9 3 6
 * 结果输出:
 * 7 3 0 0 7 7 2 8 5 7 1 8 2 7 1 5 6 4 3 0 8 7 4 1 2 8 4 8 1 4 1 5 1 3 0 5 0 3 7 6
 * <p>
 * 测试用例2:
 * 33 26
 * 5 9 2 3 7 4 9 9 0 2 6 6 1 3 8 3 2 1 9 8 4 3 1 3 3 7 5 3 9 3 1 3 1
 * 4 2 8 3 5 1 0 5 7 4 5 0 2 5 0 3 9 7 3 6 8 4 4 9 7 1
 * 结果输出:
 * 5 9 2 3 7 5 0 3 3 1 0 1 2 4 4 0 6 7 0 0 9 3 5 3 1 1 2 2 3 8 1 0 2
 */
public class PlusLinkedList {
    static class LinkNode {
        /**
         * 节点值
         */
        private int value;
        /**
         * 下一个节点
         */
        private LinkNode next;

        public LinkNode(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();

        // 得到逆序的链表
        LinkNode nLinkHead = getResLink(n, sc);
        LinkNode mLinkHead = getResLink(m, sc);

        // 链表相加
        printLink(plusList(nLinkHead, mLinkHead));
    }

    /**
     * 得到反序的链表
     */
    private static LinkNode getResLink(int n, Scanner sc) {
        LinkNode headNode = null;
        for (int i = 0; i < n; i++) {
            LinkNode node = new LinkNode(sc.nextInt());
            if (headNode != null) {
                node.next = headNode;
            }
            headNode = node;
        }
        return headNode;
    }

    /**
     * 两个链表生成相加链表
     *
     * @param nNode n链表的头节点
     * @param mNode m链表的头节点
     * @return
     */
    private static LinkNode plusList(LinkNode nNode, LinkNode mNode) {
        // 边界值判断
        if (nNode == null) {
            return mNode;
        } else if (mNode == null) {
            return nNode;
        }

        LinkNode resNodeHead = null;
        int flag = 0;
        while (nNode != null || mNode != null) {
            int a = nNode == null ? 0 : nNode.value;
            int b = mNode == null ? 0 : mNode.value;

            int ab = a + b + flag;
            LinkNode node = new LinkNode(ab % 10);
            flag = ab / 10;

            if (resNodeHead != null) {
                node.next = resNodeHead;
            }
            resNodeHead = node;

            if (nNode != null) {
                nNode = nNode.next;
            }
            if (mNode != null) {
                mNode = mNode.next;
            }
        }

        if (flag == 1) {
            LinkNode node = new LinkNode(1);
            node.next = resNodeHead;
            resNodeHead = node;
        }

        return resNodeHead;
    }

    /**
     * 打印链表节点值
     */
    private static void printLink(LinkNode node) {
        if (node == null) {
            return;
        }
        LinkNode p = node;
        do {
            System.out.print(p.value + " ");
            p = p.next;
        } while (p != null);
        System.out.println();
    }
}

双向链表

单向链表的问题

  • 单向链表,查找的方向只能是一个方向,而双向链表可以向前或者向后查找。
  • 单向链表不能自我删除,需要靠辅助节点 ,而双向链表,则可以自我删除。

双向链表CRUD操作

思路分析
  • 遍历:方法和单向链表一样,只不过可以向前,也可以向后查找。
  • 添加:((默认添加到双向链表的最后)先找到双向链表的最后这个节点(cursor),然后 cursor.next = newNode; newNode.pre = cursor;
  • 修改:方法和单向链表一样。
  • 删除:直接找到要删除的结点(cursor),然后 cursor.pre.next = cursor.next; cursor.next.pre = cursor.pre;
代码实现
public class DoubleLinkedListDemo {
    /**
     * 定义一个双向链表的结点对象
     */
    static class LinkedNode {
        private int value;
        private LinkedNode next;
        private LinkedNode pre;

        public LinkedNode(int value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "LinkedNode[value=" + value + "]";
        }
    }

    public static void main(String[] args) {
        LinkedNode head = createLinkedList(5, 4, 1, 3, 8, 9, 7);
        System.out.print("① 双向链表:");
        printLinkedList(head);
        LinkedNode head2 = createLinkedListByOrder(6, 8, 1, 4, 9, 3, 2);
        System.out.print("② 有序的双向链表:");
        printLinkedList(head2);
//        LinkedNode newHead = deleteNode(head, 5);
        LinkedNode newHead = deleteNode(head, 3);
//        LinkedNode newHead = deleteNode(head, 7);
        System.out.print("③ 双向链表删除:");
        printLinkedList(newHead);
    }

    /**
     * 双向链表创建(默认方式)
     */
    private static LinkedNode createLinkedList(int... values) {
        LinkedNode head = null, cursor = null;
        for (int value : values) {
            LinkedNode node = new LinkedNode(value);
            if (head == null) {
                head = node;
            } else {
                cursor.next = node;
                node.pre = cursor;
            }
            cursor = node;
        }
        return head;
    }

    /**
     * 双向链表创建(有序)
     */
    private static LinkedNode createLinkedListByOrder(int... values) {
        if (values == null || values.length == 0) {
            return null;
        }
        // 创建一个头结点
        LinkedNode tempHead = new LinkedNode(0);

        for (int value : values) {
            addByOrder(tempHead, new LinkedNode(value));
        }

        // 返回不带头结点的头结点
        LinkedNode head = tempHead.next;
        tempHead.next = null;
        return head;
    }

    private static void addByOrder(LinkedNode tempHead, LinkedNode node) {
        LinkedNode cursor = tempHead;
        // cursor的下一个结点
        LinkedNode next;
        while (cursor.next != null) {
            next = cursor.next;
            if (cursor.next.value > node.value) {
                // 位置找到,进行结点插入
                node.next = next;
                next.pre = node;
                cursor.next = node;
                node.pre = next;
                break;
            }
            cursor = next;
        }
        if (cursor.next == null) {
            cursor.next = node;
            node.pre = cursor;
        }
    }

    /**
     * 删除结点
     */
    private static LinkedNode deleteNode(LinkedNode head, int value) {
        if (head == null) {
            System.out.println("链表空,不能删除~~");
            return null;
        }
        // 如果删除的是头结点
        if (head.value == value) {
            head = head.next;
            head.pre = null;
            return head;
        }
        LinkedNode cursor = head;
        while (cursor != null) {
            if (cursor.value == value) {
                cursor.pre.next = cursor.next;
                // 如果是最后一个节点,就不需要执行下面这句话,否则出现空指针
                if (cursor.next != null) {
                    cursor.next.pre = cursor.pre;
                }
                break;
            }
            cursor = cursor.next;
        }
        return head;
    }

    /**
     * 打印链表
     * @param head
     */
    private static void printLinkedList(LinkedNode head) {
        if (head == null) {
            System.out.println("null");
            return;
        }
        LinkedNode cursor = head;
        System.out.print("null <- ");
        while (cursor != null) {
            System.out.printf(cursor.next == null ? "%d -> " : "%d <=> ", cursor.value);
            cursor = cursor.next;
        }
        System.out.println("null");
    }
}
  • 结果输出
① 双向链表:null <- 5 <=> 4 <=> 1 <=> 3 <=> 8 <=> 9 <=> 7 -> null
② 有序的双向链表:null <- 1 <=> 2 <=> 3 <=> 4 <=> 6 <=> 8 <=> 9 -> null
③ 双向链表删除:null <- 5 <=> 4 <=> 1 <=> 8 <=> 9 <=> 7 -> null

单向环形链表

Josephu问题

  • 设编号为1,2,… n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m 的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,直到所有人出列为止,由此产生一个出队编号的序列。
  • 实现思路:用一个不带头结点的循环链表来处理 Josephu 问题,先构成一个有 n 个结点的单循环链表,然后由 k 结点起从 1 开始计数,计到 m 时,对应结点从链表中删除,然后再从被删除结点的下一个结点又从 1 开始计数,直到最后一个结点从链表中删除,算法结束。

代码实现

public class CircleSingleLinkedListDemo {
    static class LinkedNode {
        private int value;
        private LinkedNode next;

        public LinkedNode(int value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "LinkedNode[value=" + value + "]";
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入环形链表的大小(n):");
        int n = sc.nextInt();
        LinkedNode first = createCircleSingleLinkedList(n);
        System.out.print("生成环形链表:");
        printLinkedList(first);
        System.out.print("请输入编号(k):");
        int k = sc.nextInt();
        System.out.print("请输入数字(m):");
        int m = sc.nextInt();
        System.out.print("打印输出约瑟夫出队编号序列:");
        printJosephuQueue(first, n, k, m);
    }

    private static LinkedNode createCircleSingleLinkedList(int n) {
        if (n <= 0) {
            return null;
        }
        LinkedNode first = null, cursor = null;
        for (int i = 1; i <= n; i++) {
            LinkedNode node = new LinkedNode(i);
            if (first == null) {
                first = node;
                // 形成环
                first.next = first;
                cursor = first;
            } else {
                cursor.next = node;
                node.next = first;
                cursor = node;
            }
        }
        return first;
    }

    private static void printLinkedList(LinkedNode first) {
        if (first == null) {
            System.out.println("链表空~~");
            return;
        }
        LinkedNode cursor = first;
        while (cursor.next != first) {
            System.out.printf("%d\t", cursor.value);
            cursor = cursor.next;
        }
        System.out.printf("%d\t", cursor.value);
        System.out.println();
    }

    private static void printJosephuQueue(LinkedNode first, int n, int k, int m) {
        if (first == null || k < 1 || k > n || m < 1) {
            System.out.println("输入参数有误~~");
            return;
        }
        // 1、创建一个辅助指针,并指向环形链表的最后一个节点
        LinkedNode cursor = first;
        while (cursor.next != first) {
            cursor = cursor.next;
        }
        // 2、将first、cursor移动k-1次
        for (int i = 0; i < k - 1; i++) {
            first = first.next;
            cursor = cursor.next;
        }
        // 3、开始数m下,即移动m-1次,找到要出队的结点,并完成出队
        while (true) {
            if (cursor == first) {
                // 说明环形链表只剩下最后一个结点
                System.out.print(cursor.value);
                break;
            }
            // 移动m-1次
            for (int i = 0; i < m - 1; i++) {
                first = first.next;
                cursor = cursor.next;
            }
            System.out.printf("%d\t", first.value);
            first = first.next;
            cursor.next = first;
        }
    }
}
  • 测试输出:
请输入环形链表的大小(n):10
生成环形链表:1	2	3	4	5	6	7	8	9	10	
请输入编号(k):3
请输入数字(m):6
打印输出约瑟夫出队编号序列:8	4	1	9	7	10	3	2	6	5
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java后端架构-2023.xmind是一份关于Java后端架构在2023年中可能面临的各种挑战和技能要求的思维导图。 首先,作为Java后端架构,技术能力是最基本的要求之一。需要具备扎实的Java编程技能,熟悉Java的开发框架和工具,如Spring、Hibernate等。同时,掌握主流的数据库系统,如MySQL、Oracle等。对微服务架构和云计算平台有一定的了解和实践经验,如Docker、Kubernetes等。 其次,架构设计能力也是核心要求。需要具备良好的架构思维,能够根据业务需求设计合理的系统架构,并保证系统的可伸缩性、高性能、高可用性和安全性。对于分布式系统、消息队列、缓存、负载均衡等技术有深入的理解和应用能力。 此外,团队协作能力也是不可忽视的。作为架构,需要与产品经理、项目经理、开发团队以及其他相关部门进行良好的沟通和协作,理解和把握业务需求,并能够将架构设计有效地传递给开发团队。善于团队管理和培养能力,能够引导团队成员解决技术难题。 最后,不断学习和适应新技术也是非常重要的。在技术领域,变化日新月异,作为架构需要保持敏锐的技术判断力,能够及时了解和掌握新的技术趋势,并应用到实际项目中。 综上所述,Java后端架构-2023.xmind介绍了未来Java后端架构的技能要求和面临的挑战。通过不断学习和提升,拥有扎实的技术基础和良好的架构设计能力,具备团队合作和沟通能力,以及不断学习和适应新技术,才能在竞争激烈的市场中脱颖而出,成为优秀的Java后端架构

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

讲文明的喜羊羊拒绝pua

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值