稀疏矩阵
public class SparceArray {
public static void main(String[] args) {
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[5][3] = 155;
System.out.println("原始二维数组");
for (int[] row : chessArr1
) {
for (int data : row
) {
System.out.printf("%d\t", data);
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[0].length; j++) {
if (chessArr1[i][j] != 0) {
sum++;
}
}
}
//创建稀疏数组
int sparseArray[][] = new int[sum + 1][3];
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
//将非0值存入数组
int count = 1;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[0].length; j++) {
if (chessArr1[i][j] != 0) {
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chessArr1[i][j];
count++;
}
}
}
//输出稀疏数组
System.out.println("得到的稀疏数组");
for (int row[] : sparseArray
) {
for (int a : row
) {
System.out.printf("%d\t", a);
}
System.out.println();
}
System.out.println("恢复后的数组");
//恢复稀疏数组
int chessArr2[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i = 1; i < sparseArray.length; i++){
chessArr2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
for (int[] row : chessArr2
) {
for (int data : row
) {
System.out.printf("%d\t",data);
}
System.out.println();
}
}
}
数组实现循环队列
public class ArrayQueue {
public static void main(String[] args) {
Queue queue = new Queue(3);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop){
System.out.println("s,显示队列");
System.out.println("e,退出程序");
System.out.println("a,添加数据到队列");
System.out.println("g,从队列中取数据");
System.out.println("h,显示队列头");
key = scanner.next().charAt(0);
switch (key){
case 's':
queue.showQueue();
System.out.println();
break;
case 'a':
System.out.println("请输入数值");
int value = scanner.nextInt();
queue.addQueue(value);
break;
case 'g':
try {
int res = queue.getQueue();
System.out.printf("取出的数据是%d",res);
System.out.println();
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = queue.headQueue();
System.out.printf("队列头数据是%d",res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
static class Queue{
private int maxSize;
private int front;//头
private int rear; //尾
private int[] arr;
public Queue(int arrMaxSize){
maxSize = arrMaxSize;
arr = new int[maxSize];
}
public boolean isFull(){
return (rear + 1) % maxSize == front;
}
public boolean isEmpty(){
return rear == front;
}
//添加数据
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 temp = arr[front];
front = (front + 1) % maxSize;
return temp;
}
//显示队列中的数据
public void showQueue(){
if (isEmpty()){
System.out.println("队列为空,没有数据");
return;
}
for (int i = front; i < front + size() ; i++) {
System.out.printf("arr[%d] %d", i % maxSize, arr[i % maxSize]);
System.out.println();
}
}
//求出当前队列中的个数
public int size(){
return (rear + maxSize - front) % maxSize;
}
//显示队列的头数据
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("队列是空的");
}
return arr[front];
}
}
}
链表反转
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public class 链表反转 {
public static ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
while (cur!=null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public static ListNode deleteList(ListNode head, int value){
ListNode temp = head;
boolean flag = false;
while (true){
if (temp.next == null){
break;
}
if (temp.next.val == value){
flag = true;
break;
}
temp = temp.next;
}
//判断flag
if (flag){
temp.next = temp.next.next;
}else {
System.out.println("没有找到要删除的节点");
}
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(2);
ListNode cur = head;
for (int i = 3; i <6 ; i++) {
cur.next = new ListNode(i);
cur = cur.next;
}
ListNode res = reverseList(head);
while (res != null){
System.out.println(res.val);
res = res.next;
}
res = deleteList(cur, 3);
while (res != null){
System.out.println(res.val);
res = res.next;
}
}
}
双向链表
package cc;
/**
* @Author:wjy
* @Date: 2023/5/23 15:47
*/
public class DoubleLinkedListDemo {
public static void main(String[] args) {
System.out.println("双向链表的创建");
//创建节点
HeroNode heroNode1 = new HeroNode(1, "松江", "及时雨");
HeroNode heroNode2 = new HeroNode(2, "松江", "及时雨");
HeroNode heroNode3 = new HeroNode(3, "松江", "及时雨");
HeroNode heroNode4 = new HeroNode(4, "松江", "及时雨");
DoubleLinkedList doubleLinkList = new DoubleLinkedList();
doubleLinkList.add(heroNode1);
doubleLinkList.add(heroNode2);
doubleLinkList.add(heroNode3);
doubleLinkList.add(heroNode4);
doubleLinkList.list();
HeroNode newHeroNode = new HeroNode(4, "王俊凯", "杀掉");
doubleLinkList.update(newHeroNode);
System.out.println("修改之后的内容");
doubleLinkList.list();
System.out.println("删除之后的内容");
doubleLinkList.del(2);
doubleLinkList.list();
}
}
class DoubleLinkedList{
private HeroNode head = new HeroNode(0, "", "");
public HeroNode getHead(){
return head;
}
//遍历链表
public void list(){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
while (true){
if (temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
//添加链表
public void add(HeroNode heroNode){
HeroNode temp = head;
while (true){
if (temp.next == null){
break;
}
temp = temp.next;
}
//形成一个双向链表
temp.next = heroNode;
heroNode.pre = temp;
}
//修改节点
public void update(HeroNode heroNode){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.no == heroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.name = heroNode.name;
temp.nickName = heroNode.nickName;
}else {
System.out.println("没有找到编号"+heroNode.no+"的节点");
}
}
//删除节点
public void del(int no){
if (head.next == null){
System.out.println("链表为空,无法进行删除");
return;
}
HeroNode temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.no == no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.pre.next = temp.next;
if (temp.next != null){
temp.next.pre = temp.pre;
}
}
else {
System.out.println("没有找到编号"+ no +"的节点");
}
}
}
class HeroNode{
public int no;
public String name;
public String nickName;
public HeroNode next;
public HeroNode pre;
public HeroNode(int no, String name, String nickName){
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickName='" + nickName + '\'' +
'}';
}
}
约瑟夫问题
package shujujiegou;
import javax.sound.midi.VoiceStatus;
/**
* @Author:wjy
* @Date: 2023/5/25 15:30
*/
public class Josepfu {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.showBoy();
circleSingleLinkedList.countBoy(1, 2, 5);
}
}
//创建环形单向列表
class CircleSingleLinkedList{
private Boy first = new Boy(-1);
public void addBoy(int nums){
if (nums < 1){
System.out.println("nums的值不正确");
return;
}
Boy curBoy = null;
for (int i = 1; i <= nums; i ++) {
Boy boy = new Boy(i);
if (i == 1){
first = boy;
first.setNext(first);
curBoy = first;
}
else {
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;
}
}
}
public void showBoy(){
if (first == null){
System.out.println("没有任何小孩");
return;
}
Boy curBoy = first;
while (true){
System.out.println("小孩的编号为" + curBoy.getNo());
if (curBoy.getNext() == first){
break;
}
curBoy = curBoy.getNext();
}
}
public void countBoy(int startNo, int count, int nums){
if (first == null || startNo < 1 || startNo > nums){
System.out.println("参数输入有错");
return;
}
//创建辅助指针
Boy helper = first;
while (true){
if (helper.getNext() == first){
break;
}
helper = helper.getNext();
}
for (int i = 0; i < startNo - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
while (true){
if (helper == first){
break;
}
for (int j = 0; j < count - 1; j++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.println("小孩" + first.getNo() + "出圈");
first = first.getNext();
helper.setNext(first);
}
System.out.println("最后下的小孩编号为" + first.getNo());
}
}
class Boy{
private int no;
private Boy next;
public Boy(int no){
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Boy getNext() {
return next;
}
public void setNext(Boy next) {
this.next = next;
}
}
数组模拟栈
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(4);
String key = "";
boolean loop = true;
Scanner scanner = new Scanner(System.in);
while (loop){
System.out.println("show:显示栈");
System.out.println("exit:退出栈");
System.out.println("push:添加栈中内容");
System.out.println("pop:输出栈中内容");
System.out.println("请输入你的选择:");
key = scanner.next();
switch (key){
case "show":
stack.list();
break;
case "push":
stack.push(scanner.nextInt());
break;
case "pop":
try {
System.out.println("出栈的数据是" + stack.pop());
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case "exit":
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序结束");
}
}
class ArrayStack{
private int maxsize;
private int[] stack;
private int top = -1; //栈顶
public ArrayStack(int maxsize){
this.maxsize = maxsize;
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 list(){
if (isEmpty()){
System.out.println("表中没有数据");
return;
}
for (int i = top; i >= 0 ; i--) {
System.out.printf("stack[%d] = %d\n", i, stack[i]);
}
}
}
模拟计算器
package shujujiegou;
/**
* @Author:wjy
* @Date: 2023/5/27 11:01
*/
public class Calculator {
public static void main(String[] args) {
String expression = "300+2*6-2";
ArrayStack2 numStack = new ArrayStack2(10);
ArrayStack2 operStack = new ArrayStack2(10);
//定义相关变量
int index = 0;
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' '; //每次扫描得到的char 保存到ch
String keepNum = "";
while (true) {
ch = expression.substring(index, index + 1).charAt(0);
//判断ch
if (operStack.isOper(ch)) {
if (!operStack.isEmpty()) {
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
//当前操作符如符号栈
operStack.push(ch);
} else {
operStack.push(ch);
}
} else {
//符号栈为空直接入栈
operStack.push(ch);
}
}
//如果事数值 直接入数栈
else {
//numStack.push(ch - 48);
//处理多位数值时 继续扫描
keepNum += ch;
if (index == expression.length() -1){
numStack.push(Integer.parseInt(keepNum));
}else {
//判断下一位是是否为数字
if (operStack.isOper(expression.substring(index + 1,index + 2).charAt(0))){
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index >= expression.length()) {
break;
}
}
while (true){
//符号栈为空 计算为最后结果
if(operStack.isEmpty()){
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
System.out.println("表达式:" + expression + "的计算结果为:" + numStack.pop());
}
}
class ArrayStack2 {
private int maxsize;
private int[] stack;
private int top = -1; //栈顶
public ArrayStack2(int maxsize) {
this.maxsize = maxsize;
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 peek() {
return stack[top];
}
//出栈
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈中没有数据");
}
int value = stack[top];
top--;
return value;
}
//显示栈的情况
public void list() {
if (isEmpty()) {
System.out.println("表中没有数据");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d] = %d\n", i, stack[i]);
}
}
//返回运算符的优先级
public int priority(int oper) {
if (oper == '*' || oper == '/') {
return 1;
} else if (oper == '+' || oper == '-') {
return 0;
} else {
return -1;
}
}
//判断是不是运算符
public boolean isOper(char val) {
return val == '+' || val == '-' || val == '*' || val == '-';
}
//计算方法
public int cal(int num1, int num2, int oper) {
int res = 0;
switch (oper) {
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
}
逆波兰、中缀转后缀
public class PolandNotation {
public static void main(String[] args) {
String sufferExpression = "3 4 + 5 * 6 -";
//存入ArrayList中
List<String> strings = getListString(sufferExpression);
int res = calculate(strings);
System.out.println(res);
String expression = "1+((2+3)*4)-5";
List<String> strings1 = parseSuffixExpressionList(toInfixExpressionList(expression));
System.out.println(toInfixExpressionList(expression));
System.out.println(strings1);
System.out.println(calculate(strings1));
}
//中缀转后缀
public static List<String> parseSuffixExpressionList(List<String> ls){
//符号栈
Stack<String> s1 = new Stack<>();
List<String> s2 = new ArrayList<>();
for (String item:ls){
if (item.matches("\\d+")){
s2.add(item);
}else if (item.equals("(")){
s1.push(item);
}else if(item.equals(")")){
//右括号需要弹出符号栈中的运算符并压入S2,直到遇到左括号
while (!s1.peek().equals("(")){
s2.add(s1.pop());
}
//将( 弹出
s1.pop();
}else {
//当item的优先级小于栈顶
while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)){
s2.add(s1.pop());
}
s1.push(item);
}
}
while (s1.size() != 0){
s2.add(s1.pop());
}
return s2;
}
//字符转中缀表达式
public static List<String> toInfixExpressionList(String s){
List<String> ls = new ArrayList<>();
int i = 0;
String str;
char c;
do {
//非数值 加入ls中
if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) >57){
ls.add("" + c);
i++;
}else {
//数值
str = "";
while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57){
str += c;
i++;
}
ls.add(str);
}
}while (i < s.length());
return ls;
}
public static List<String> getListString(String sufferExpression){
String[] split = sufferExpression.split(" ");
List<String> list = new ArrayList<>();
for (String ele: split) {
list.add(ele);
}
return list;
}
//后缀表达式计算
public static int calculate(List<String> ls){
Stack<String> stack = new Stack<>();
for (String item : ls){
if (item.matches("\\d+")){
//入栈
stack.push(item);
}else {
//弹出两个数
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if (item.equals("+")){
res = num1 + num2;
}else if (item.equals("-")){
res = num1 - num2;
}else if (item.equals("*")){
res = num1 * num2;
}else if (item.equals("/")){
res = num1 / num2;
}else {
throw new RuntimeException("运算符有误");
}
stack.push(String.valueOf(res));
}
}
return Integer.parseInt(stack.pop());
}
}
//判定运算符的优先级
class Operation{
private static int ADD = 1;
private static int SUB = 1;
private static int MUL = 2;
private static int DIV = 2;
public static int getValue(String operation){
int result = 0;
switch (operation){
case "+":
result = ADD;
break;
case "-":
result = SUB;
break;
case "*":
result = MUL;
break;
case "/":
result = DIV;
break;
default:
System.out.println("不存在改运算符");
break;
}
return result;
}
}