数据结构与算法之稀疏数组、队列、链表、栈、递归

稀疏数组

public class Sparsearray {
    public static void main(String[] args) {
        int[][] arr = new int[10][10];
        arr[1][2] = 1;
        arr[2][4] = 2;
        System.out.println("原数组");
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.print(" "+anInt+" ");
            }
            System.out.println();
        }
        //得到数组非零元素个数
        int sum = 0;
        for (int[] ints : arr) {
            for (int anInt : ints) {
                if (anInt != 0){
                    sum ++;
                }
            }
        }
        //创建稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        sparseArr[0][0] = 10;
        sparseArr[0][1] = 10;
        sparseArr[0][2] = sum;
        int count = 1;
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                if (arr[i][j] != 0){
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = arr[i][j];
                    count++;
                }
            }
        }
        System.out.println("稀疏数组");
        for (int[] ints : sparseArr) {
            for (int anInt : ints) {
                System.out.print(" "+anInt+" ");
            }
            System.out.println();
        }
        //恢复数组
        int[][] data = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            data[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        System.out.println("恢复后的数组");
        for (int[] ints : data) {
            for (int anInt : ints) {
                System.out.print(" "+anInt+" ");
            }
            System.out.println();
        }
    }
}

队列

数组模拟环形队列

  • front指向队列的第一个元素。
  • rear指向队列的最后一个元素的后一个位置。
  • 队满条件为:(rear + 1) % maxSize == front。
  • 队空条件为:front == rear。
  • 队列元素个数为:(rear + maxSize - front) % maxSize
public class Queue {
    public static void main(String[] args) {
        try {
            ArrQueue arrQueue = new ArrQueue(3);
            System.out.println("队列是否为空");
            System.out.println(arrQueue.isEmpty());
            System.out.println("队列是否为满");
            System.out.println(arrQueue.isFull());
            System.out.println("加入1");
            arrQueue.addQueue(1);
            System.out.println("加入2");
            arrQueue.addQueue(2);
            System.out.println("加入3");
            arrQueue.addQueue(3);
            System.out.println("队列元素");
            arrQueue.showQueue();
            System.out.println("队头元素");
            System.out.println(arrQueue.headQueue());
            System.out.println("取出元素");
            System.out.println(arrQueue.getQueue());
            System.out.println(arrQueue.getQueue());
            System.out.println(arrQueue.getQueue());
            System.out.println(arrQueue.getQueue());
            System.out.println("队列是否为空");
            System.out.println(arrQueue.isEmpty());
            System.out.println("队列是否为满");
            System.out.println(arrQueue.isFull());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

class ArrQueue{

    private int maxSize;
    private int front;//指向对头元素
    private int rear;//指向队尾,指向队尾后一个位置
    private int[] arr;

    public ArrQueue(int maxSize){
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

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

    public boolean isEmpty(){
        return front == rear;
    }

    public void addQueue(int n){
        if (isFull()) {
            System.out.println("队列满了");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    public int getQueue(){
        if (isEmpty()) {
            throw new RuntimeException("队列空了");
        }
        int data = arr[front];
        front = (front + 1) % maxSize;
        return data;
    }

    public void showQueue(){
        if (isEmpty()) {
            System.out.println("队列空了");
            return;
        }
        for (int i = front; i < size(); i++) {
            System.out.println(" "+arr[i % maxSize]+" ");
        }
    }

    public int headQueue(){
        if (isEmpty()) {
            throw new RuntimeException("队列空了");
        }
        return arr[front];
    }

    public int size(){
        return (rear + maxSize - front) % maxSize;
    }
}

链表

单链表

public class SingleLinkedListTest {
    public static void main(String[] args) {
        SingleLinkedList list = new SingleLinkedList();
        list.add(new Node(1, "张三", 23));
        list.add(new Node(2, "李四", 99));
        list.add(new Node(3, "王五", 2));
        list.show();
        System.out.println("=====================");
        list.reverse();
        list.show();
        System.out.println("=====================");
        list.update(new Node(1, "孙悟空", 500));
        list.show();
        System.out.println("=====================");
        list.update(new Node(4, "孙悟空", 500));
        list.show();
        System.out.println("=====================");
        list.delete(new Node(1, "孙悟空", 500));
        list.show();
        System.out.println("=====================");
        list.delete(new Node(1, "孙悟空", 500));
        list.show();
    }
}

class SingleLinkedList{

    private Node head = new Node();

    public SingleLinkedList() {
        head.setNext(null);
    }

    public void add(Node node){
        node.setNext(head.getNext());
        head.setNext(node);
    }

    public void addBySort(Node node){
        Node temp = head;
        while (temp.getNext() != null){
            if (temp.getNext().getAge() < node.getAge()){
                temp = temp.getNext();
            } else {
                break;
            }
        }
        node.setNext(temp.getNext());
        temp.setNext(node);
    }

    public void update(Node node){
        if (isEmpty()){
            System.out.println("链表为空");
            return;
        }
        Node temp = head.getNext();
        boolean flag = false;
        while (temp != null){
            if (temp.getId() == node.getId()) {
                flag = true;
                break;
            } else {
                temp = temp.getNext();
            }
        }
        if (flag) {
            temp.setName(node.getName());
            temp.setAge(node.getAge());
        } else {
            System.out.println("没有找到");
        }
    }

    public void delete(Node node){
        if (isEmpty()){
            System.out.println("链表为空");
            return;
        }
        Node temp = head;
        boolean flag = false;
        while (temp.getNext() != null){
            if (temp.getNext().getId() == node.getId()) {
                flag = true;
                break;
            } else {
                temp = temp.getNext();
            }
        }
        if (flag) {
            temp.setNext(temp.getNext().getNext());
        } else {
            System.out.println("没有找到");
        }
    }

    public void reverse(){
        if (isEmpty()){
            System.out.println("链表为空");
            return;
        }
        Node temp = head.getNext();
        head.setNext(null);
        while (temp != null){
            Node node = new Node();
            node.setId(temp.getId());
            node.setName(temp.getName());
            node.setAge(temp.getAge());
            node.setNext(temp.getNext());
            add(node);
            temp = temp.getNext();
        }

    }

    public boolean isEmpty(){
        return head.getNext() == null;
    }

    public void show(){
        if (isEmpty()){
            System.out.println("链表为空");
            return;
        }
        Node temp = head.getNext();
        while (temp != null){
            System.out.println(temp);
            temp = temp.getNext();
        }
    }
}

class Node{

    private int id;
    private String name;
    private int age;
    private Node next;

    public Node() {
        next = null;
    }

    public Node(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.next = null;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

约瑟夫环

public class JosephusTest {
    public static void main(String[] args) {
        CircleSingleLinkedList list = new CircleSingleLinkedList();
        list.add(5);
        list.show();
        System.out.println("==================");
        list.out(3, 3);
    }
}

class CircleSingleLinkedList{

    private Node first;

    public CircleSingleLinkedList() {
        first = null;
    }

    public void add(int count){
        if (count < 1) {
            System.out.println("数字不对");
            return;
        }
        Node temp = null;
        for (int i = 1; i <= count; i++) {
            Node node = new Node(i);
            if (i == 1) {
                first = node;
                first.setNext(first);
                temp = first;
            } else {
                temp.setNext(node);
                node.setNext(first);
                temp = temp.getNext();
            }
        }
    }

    public void out(int k, int m){
        if (k < 1 || m < 1) {
            System.out.println("数字不对");
            return;
        }
        Node temp = first;
        while (temp.getNext() != first) {
            temp = temp.getNext();
        }
        for (int i = 0; i < k - 1; i++) {
            first = first.getNext();
            temp = temp.getNext();
        }
        while (first != temp){
            for (int i = 0; i < m - 1; i++) {
                first = first.getNext();
                temp = temp.getNext();
            }
            System.out.println(first);
            first = first.getNext();
            temp.setNext(first);
        }
        System.out.println(first);
    }

    public void show(){
        if (first == null) {
            System.out.println("环为空");
            return;
        }
        Node temp = first;
        System.out.println(temp);
        temp = temp.getNext();
        while (temp != first) {
            System.out.println(temp);
            temp = temp.getNext();
        }
    }
}

class Node{

    private int id;
    private Node next;

    public Node() {
        next = null;
    }

    public Node(int id) {
        this.id = id;
        this.next = null;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "id=" + id +
                '}';
    }
}

用数组模拟栈

public class ArrayStackTest {
    public static void main(String[] args) {
        try {
            Stack stack = new Stack(3);
            System.out.println("栈是否为空");
            System.out.println(stack.isEmpty());
            System.out.println("栈是否为满");
            System.out.println(stack.isFull());
            System.out.println("压入1");
            stack.push(1);
            System.out.println("压入2");
            stack.push(2);
            System.out.println("压入3");
            stack.push(3);
            System.out.println("压入4");
            stack.push(4);
            System.out.println("遍历");
            stack.show();
            System.out.println("弹出");
            System.out.println(stack.pop());
            System.out.println("弹出");
            System.out.println(stack.pop());
            System.out.println("弹出");
            System.out.println(stack.pop());
            System.out.println("弹出");
            System.out.println(stack.pop());
            System.out.println("栈是否为空");
            System.out.println(stack.isEmpty());
            System.out.println("栈是否为满");
            System.out.println(stack.isFull());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Stack{

    private int maxSize;
    private int[] stack;
    private int top;

    public Stack(int maxSize) {
        this.maxSize = maxSize;
        this.top = -1;
        this.stack = new int[maxSize];
    }

    public boolean isFull(){
        return top == maxSize - 1;
    }

    public boolean isEmpty(){
        return top == -1;
    }

    public void push(int value){
        if (isFull()) {
            System.out.println("栈满了");
            return;
        }
        top++;
        stack[top] = value;
    }

    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("栈空了");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public void show(){
        if (isEmpty()) {
            System.out.println("栈空了");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.print(" "+stack[i]+" ");
        }
    }
}

简易计算器

public class CalculatorTest {
    public static void main(String[] args) {
        String expression = "300*6-4/2+30";
        char[] chars = expression.toCharArray();
        Stack numberStack = new Stack(10);
        Stack operatorStack = new Stack(10);
        for (int i = 0; i < chars.length; i++) {
            if (operatorStack.isOperator(chars[i])) {
                if (!operatorStack.isEmpty()) {
                    while (!operatorStack.isEmpty() && operatorStack.priority(chars[i]) <= operatorStack.priority((char) operatorStack.peek())) {
                        int right = numberStack.pop();
                        int left = numberStack.pop();
                        char operator = (char) operatorStack.pop();
                        int result = numberStack.cal(right, left, operator);
                        numberStack.push(result);
                    }
                }
                operatorStack.push(chars[i]);
            } else {
                String number = chars[i] + "";
                while (i < chars.length - 1 && !operatorStack.isOperator(chars[i + 1])){
                    number += chars[i + 1];
                    i++;
                }
                numberStack.push(Integer.parseInt(number));
            }
        }
        while (!operatorStack.isEmpty()){
            int right = numberStack.pop();
            int left = numberStack.pop();
            char operator = (char) operatorStack.pop();
            int result = numberStack.cal(right, left, operator);
            numberStack.push(result);
        }
        System.out.println(numberStack.pop());
    }
}

class Stack{

    private int maxSize;
    private int[] stack;
    private int top;

    public Stack(int maxSize) {
        this.maxSize = maxSize;
        this.top = -1;
        this.stack = new int[maxSize];
    }

    public boolean isFull(){
        return top == maxSize - 1;
    }

    public boolean isEmpty(){
        return top == -1;
    }

    public void push(int value){
        if (isFull()) {
            System.out.println("栈满了");
            return;
        }
        top++;
        stack[top] = value;
    }

    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("栈空了");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public int peek(){
        return stack[top];
    }

    public int priority(char operator){
        if (operator == '*' || operator == '/') {
            return 1;
        } else if (operator == '+' || operator == '-') {
            return 0;
        } else {
            return -1;
        }
    }

    public boolean isOperator(char val) {
        return val == '*' || val == '/' || val == '+' || val == '-';
    }

    public int cal(int right, int left, char operator) {
        int result = 0;
        switch (operator) {
            case '+':
                result = left + right;
                break;
            case '-':
                result = left - right;
                break;
            case '*':
                result = left * right;
                break;
            case '/':
                result = left / right;
                break;
        }
        return result;
    }

    public void show(){
        if (isEmpty()) {
            System.out.println("栈空了");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.print(" "+stack[i]+" ");
        }
    }

    @Override
    public String toString() {
        return "Stack{" +
                "stack=" + Arrays.toString(stack) +
                '}';
    }
}

逆波兰表达式计算

public class PolandNotation {
    public static void main(String[] args) {
        String expression = "3 4 + 5 * 6 -";
        List<String> list = getListString(expression);
        System.out.println(calculate(list));
    }

    public static List<String> getListString(String expression) {
        String[] strings = expression.split(" ");
        return new ArrayList<>(Arrays.asList(strings));
    }

    public static int calculate(List<String> list){
        Stack<String> stack = new Stack<>();
        for (String s : list) {
            if (s.matches("\\d+")) {
                stack.push(s);
            } else {
                int right = Integer.parseInt(stack.pop());
                int left = Integer.parseInt(stack.pop());
                int result = 0;
                switch (s) {
                    case "+":
                        result = left + right;
                        break;
                    case "-":
                        result = left - right;
                        break;
                    case "*":
                        result = left * right;
                        break;
                    case "/":
                        result = left / right;
                        break;
                }
                stack.push(result + "");
            }
        }
        return Integer.parseInt(stack.pop());
    }
}

中缀表达式转后缀表达式

public class InfixSuffix {
    public static void main(String[] args) {
        String expression = "10+((2+3)*4)-5";
        List<String> list = getInfixList(expression);
        System.out.println(getSuffixList(list));
    }

    public static List<String> getInfixList(String expression) {
        List<String> list = new ArrayList<>();
        String number = "";
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (c < 48 || c > 57) {
                list.add(c + "");
            } else {
                number += c;
                while (i < expression.length() - 1) {
                    c = expression.charAt(i + 1);
                    if (c <= 57 && c >= 48){
                        number += c;
                        i++;
                    } else {
                        break;
                    }
                }
                list.add(number);
                number = "";
            }
        }
        return list;
    }

    public static List<String> getSuffixList(List<String> infixList) {
        List<String> suffixList = new ArrayList<>();
        Stack<String> stack = new Stack<>();
        for (String s : infixList) {
            if (s.matches("\\d+")) {
                suffixList.add(s);
            } else if (s.equals("(")) {
                stack.push(s);
            } else if (s.equals(")")) {
                while (!stack.peek().equals("(")) {
                    suffixList.add(stack.pop());
                }
                stack.pop();
            } else {
                while (!stack.empty() && priority(s) <= priority(stack.peek())) {
                    suffixList.add(stack.pop());
                }
                stack.push(s);
            }
        }
        while (!stack.empty()) {
            suffixList.add(stack.pop());
        }
        return suffixList;
    }

    public static int priority(String operator){
        if (operator.equals("*") || operator.equals("/")) {
            return 1;
        } else if (operator.equals("+")|| operator.equals("-")) {
            return 0;
        } else {
            return -1;
        }
    }
}

递归

迷宫问题

public class LabyrinthTest {
    public static void main(String[] args) {
        //0表示没有走过,1表示墙,2表示可以通过,3表示已经搜索过,但走不通
        int[][] ints = new int[8][8];
        for (int i = 0; i < 8; i++) {
            ints[0][i] = 1;
            ints[7][i] = 1;
        }
        for (int i = 0; i < 8; i++) {
            ints[i][0] = 1;
            ints[i][7] = 1;
        }
        ints[3][1] = 1;
        ints[3][2] = 1;
        ints[3][4] = 1;
        ints[6][5] = 1;
        ints[5][5] = 1;
        ints[4][5] = 1;
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                System.out.print(" "+ints[i][j]+" ");
            }
            System.out.println();
        }
        getWay(ints, 1, 1);
        System.out.println();
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {
                System.out.print(" "+ints[i][j]+" ");
            }
            System.out.println();
        }
    }

    //从(1,1)出发,走到(6,6),以下,右,上,左的次序搜索
    public static boolean getWay(int[][] map, int i, int j){
        if (map[6][6] == 2) {
            return true;
        } else {
            if (map[i][j] == 0) {
                map[i][j] = 2;
                if (getWay(map, i + 1, j)) {
                    return true;
                } else if (getWay(map, i, j + 1)) {
                    return true;
                } else if (getWay(map, i - 1, j)) {
                    return true;
                } else if (getWay(map, i, j - 1)) {
                    return true;
                } else {
                    map[i][j] = 3;
                    return false;
                }
            } else {
                return false;
            }
        }
    }
}

八皇后问题

public class Queue8 {

    private static int max = 8;
    private static int[] arr = new int[max];

    public static void main(String[] args) {
        check(0);
    }

    public static boolean judge(int n) {
        for (int i = 0; i < n; i++) {
            //arr[i] == arr[n]:判断是否在同一列
            //Math.abs(n - i) == Math.abs(arr[n] - arr[i]):判断是否在同一斜线
            if (arr[i] == arr[n] || Math.abs(n - i) == Math.abs(arr[n] - arr[i])) {
                return false;
            }
        }
        return true;
    }

    public static void check(int n) {
        if (n == max) {
            print();
            return;
        }
        for (int i = 0; i < max; i++) {
            arr[n] = i;
            if (judge(n)) {
                check(n + 1);
            }
        }
    }

    public static void print() {
        for (int i : arr) {
            System.out.print(" "+i+" ");
        }
        System.out.println();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值