数据结构与算法学习笔记(Java)
程序 = 数据结构 + 算法
数据结构
- 数据结构包括:线性结构和非线性结构
线性结构
- 线性结构作为最常用的数据结构,其特点是数据元素之间存在一对一的线性关系
- 线性结构有两种不同的存储结构,即顺序存储结构和链式存储结构,顺序存储的线性表称为顺序表,顺序表中的存储元素是连续的。
- 链式存储的线性表称为链表,链表中的存储元素不一定是连续的,元素节点中存放数据元素以及相邻元素的地址信息。
- 线性结构常见有:数组,队列,链表和栈。
非线性结构
- 非线性结构包括:二维数组,多维数组,广义表,树结构,图结构。
稀疏数组
- 当一个数组中大部分元素为0,或者为同一个值的数组时,可以使用稀疏数组来保存改数组
- 稀疏数组的处理方法
- 记录数组一共有几行几列,有多少个不同的值
- 把具有不同值的元素的行列及值记录在一个小规模的数组中。从而缩小程序的规模
- 第一行存储二维数组的总行数和总列数,一共有多少个不同的值,下面存储具体值对应的位置
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210412141542272.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3Bhbl8wMzEy,size_16,color_FFFFFF,t_70#pic_center)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210412140706884.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3Bhbl8wMzEy,size_16,color_FFFFFF,t_70#pic_center)
- 二维数组转稀疏数组思路
- 遍历原始的二维数组,得到有效数据的个数sum
- 根据sum就可以创建稀疏数组sparseArr int[sum+1][3]
- 将二维数组的有效数据存入到稀疏数组
4. 稀疏数组转原始二维数组的思路
1. 先取到稀疏数组的第一行。根据第一行的数据,创建原始的二维数组
2. 再读取稀疏数组后几行的数据,并赋给原始的二维数组即可
public class SparseArray {
public static void main(String[] args) {
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
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 < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArr1[i][j] != 0){
sum++;
}
}
}
int sparseArr[][] = new int[sum+1][3];
sparseArr[0][0] = 11;
sparseArr[0][1] = 11;
sparseArr[0][2] = sum;
int count = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (chessArr1[i][j] != 0){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
System.out.println("得到的稀疏数组为。。。");
for (int i = 0; i < sparseArr.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
}
int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
for (int i = 1; i < sparseArr.length; i++) {
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
System.out.println("恢复后的二维数组。。。");
for (int[] row: chessArr2) {
for (int data: row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
File file = new File("E:\\sparseArr.txt");
try {
if (!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fileWriter);
for (int i = 0; i < sparseArr.length; i++) {
bw.write(sparseArr[i][0]+ ","+sparseArr[i][1]+","+sparseArr[i][2]);
bw.newLine();
bw.flush();
}
}catch (IOException e){
System.out.println(e);
}
String result = null;
try {
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String str = null;
while ((str = br.readLine()) != null){
builder.append(str).append(";");
}
result = builder.deleteCharAt(builder.lastIndexOf(";")).toString();
}catch (IOException e){
System.out.println(e);
}
String array[] = result.split(";");
int sparseArr1[][] = new int[array.length][3];
for (int i = 0; i < array.length; i++) {
String str[] = array[i].split(",");
sparseArr1[i][0] = Integer.parseInt(str[0]);
sparseArr1[i][1] = Integer.parseInt(str[1]);
sparseArr1[i][2] = Integer.parseInt(str[2]);
}
System.out.println("读取文件恢复的稀疏数组。。。");
for (int[] row: sparseArr1) {
for (int data: row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
}
}
队列
- 队列是一个有序列表,可以用数组或是链表来实现
- 遵循先入先出的原则,即:先存入队列的数据,要先取出,后存入的要后取出
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(3);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop){
System.out.println("s(show): 显示队列");
System.out.println("e(exit): 退出程序");
System.out.println("a(add): 添加数据到队列");
System.out.println("g(get): 从队列取数据");
System.out.println("h(head): 查看队列头的数据");
key = scanner.next().charAt(0);
switch (key){
case 's':
queue.showQueue();
break;
case 'e':
scanner.close();
loop = false;
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\t", res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = queue.headQueue();
System.out.printf("队列头的数据是%d\t", res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
System.out.println("程序退出。。。");
}
}
class ArrayQueue{
private int maxSize;
private int front;
private int rear;
private int[] arr;
public ArrayQueue(int maxSize){
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;
rear = -1;
}
public boolean isFull(){
return rear == maxSize -1;
}
public boolean isEmpty(){
return rear == front;
}
public void addQueue(int n){
if (isFull()){
System.out.println("队列满,不能加入数据");
return;
}
rear++;
arr[rear] = n;
}
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空,不能取数据");
}
front++;
return arr[front];
}
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]);
}
}
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空,没有数据");
}
return arr[front + 1];
}
}
问题分析并优化
- 目前数组使用一次就没能用,没有达到复用的效果
- 将这个数组使用算法,改进成一个环形队列,取模:%
- front变量含义做一个调整:front就指向为队列的第一个元素,也就是说arr[front]就是队列的第一个元素,front初始值=0
- rear变量的含义做一个调整:rear指向队列最后一个元素的后一个位置,因为希望空出一个空间作为约定,rear初始值=0
- 当队列满时,条件是(rear + 1) % maxSize == front
- 队列为空的条件,rear = front
- 队列中有效的数据个数:(rear + maxSize - front) % maxSize
public class CircleArrayQueueDemo {
public static void main(String[] args) {
System.out.println("测试数组模拟环形队列。。。");
CircleArray queue = new CircleArray(4);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop){
System.out.println("s(show): 显示队列");
System.out.println("e(exit): 退出程序");
System.out.println("a(add): 添加数据到队列");
System.out.println("g(get): 从队列取数据");
System.out.println("h(head): 查看队列头的数据");
key = scanner.next().charAt(0);
switch (key){
case 's':
queue.showQueue();
break;
case 'e':
scanner.close();
loop = false;
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\t", res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = queue.headQueue();
System.out.printf("队列头的数据是%d\t", res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
System.out.println("程序退出。。。");
}
}
class CircleArray{
private int maxSize;
private int front;
private int rear;
private int[] arr;
public CircleArray(int arrMaxSize){
this.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 value = arr[front];
front = (front + 1) % maxSize;
return value;
}
public void showQueue(){
if (isEmpty()){
System.out.println("队列为空,没有数据");
return;
}
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
}
}
public int size(){
return (rear + maxSize - front) % maxSize;
}
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("队列为空,没有数据");
}
return arr[front];
}
}
链表(Linked List)
- 链表是有序的列表
- 链表是以节点的方式来存储,链式存储
- 每个节点包含data域,next域:指向下一个节点
- 链表的各个节点不一定是连续存储
- 链表分带头节点的链表和没有头节点的链表,根据实际需求来确定
思路
- 添加
- 创建一个head头节点,作用就是表示单链表的头
- 后面每添加一个节点,就直接添加到链表的最后
public class SingleLinkedListDemo {
public static void main(String[] args) {
HeroNode hero1 = new HeroNode(1, "宋江", "及时雨");
HeroNode hero2 = new HeroNode(2, "卢俊义", "玉麒麟");
HeroNode hero3 = new HeroNode(3, "吴用", "智多星");
HeroNode hero4 = new HeroNode(4, "林冲", "豹子头");
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.add(hero1);
singleLinkedList.add(hero2);
singleLinkedList.add(hero3);
singleLinkedList.add(hero4);
singleLinkedList.list();
}
}
class SingleLinkedList{
private HeroNode head = new HeroNode(0, "", "");
public void add(HeroNode heroNode){
HeroNode temp = head;
while(true){
if (temp.next == null){
break;
}
temp = temp.next;
}
temp.next = heroNode;
}
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;
}
}
}
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;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
- 按编号的顺序添加
- 首先找到新添加节点的位置,是通过辅助变量(指针),通过变量来完成
- 新节点.next = temp.next
- 将temp.next = 新节点
public void addByOrder(HeroNode heroNode){
HeroNode temp = head;
boolean flag = false;
while (true){
if (temp.next == null){
break;
}
if (temp.next.no > heroNode.no){
break;
}else if (temp.next.no == heroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
System.out.printf("准备插入的编号%d 已经存在,不能加入\n", heroNode.no);
}else {
heroNode.next = temp.next;
temp.next = heroNode;
}
}
- 单链表修改节点
public void update(HeroNode newHeroNode){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.no == newHeroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.name = newHeroNode.name;
temp.nickname = newHeroNode.nickname;
}else {
System.out.printf("没有找到 编号 %d 的节点,不能修改\n", newHeroNode.no);
}
}
- 单链表删除节点
public void del(int no){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode temp = head;
boolean flag = false;
while (true){
if (temp.next == null){
break;
}
if (temp.next.no == no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.next = temp.next.next;
}else {
System.out.printf("要删除的 %d 节点不存在\n", no);
}
}
- 获取链表节点个数
public static int getLenth(HeroNode heroNode){
if (heroNode.next == null){
return 0;
}
int length = 0;
HeroNode cur = heroNode.next;
while (cur != null){
length ++;
cur = cur.next;
}
return length;
}
}
- 查找单链表中倒数第k个节点
public static HeroNode findLastIndexNode(HeroNode head, int index){
if (head.next == null){
return null;
}
int size = getLenth(head);
if (index <= 0 || index > size){
return null;
}
HeroNode cur = head.next;
for (int i = 0; i < size- index; i++) {
cur = cur.next;
}
return cur;
}
- 单链表反转
public static void reversetList(HeroNode head){
if (head.next == null || head.next.next == null){
return;
}
HeroNode cur = head.next;
HeroNode next = null;
HeroNode reverseHead = new HeroNode(0, "", "");
while (cur != null){
next = cur.next;
cur.next = reverseHead.next;
reverseHead.next = cur;
cur = next;
}
head.next = reverseHead.next;
}
- 逆序打印单链表
public static void reversePrint(HeroNode head){
if (head.next == null){
return;
}
Stack<HeroNode> stack = new Stack<>();
HeroNode cur = head.next;
while (cur != null){
stack.push(cur);
cur = cur.next;
}
while (stack.size() > 0){
System.out.println(stack.pop());
}
}
双向链表
public class DoubleLinkedListDemo {
public static void main(String[] args) {
HeroNode2 hero1 = new HeroNode2(4, "宋江", "及时雨");
HeroNode2 hero2 = new HeroNode2(3, "卢俊义", "玉麒麟");
HeroNode2 hero3 = new HeroNode2(2, "吴用", "智多星");
HeroNode2 hero4 = new HeroNode2(1, "林冲", "豹子头");
DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
doubleLinkedList.addByOrder(hero1);
doubleLinkedList.addByOrder(hero2);
doubleLinkedList.addByOrder(hero3);
doubleLinkedList.addByOrder(hero4);
doubleLinkedList.list();
HeroNode2 newHeroNode = new HeroNode2(4, "公孙胜", "入云龙");
doubleLinkedList.update(newHeroNode);
System.out.println("修改后的链表");
doubleLinkedList.list();
doubleLinkedList.del(4);
System.out.println("删除后的链表");
doubleLinkedList.list();
}
}
class DoubleLinkedList{
private HeroNode2 head = new HeroNode2(0, "", "");
public HeroNode2 getHead() {
return head;
}
public void addByOrder(HeroNode2 heroNode){
HeroNode2 temp = head;
boolean flag = false;
while (true){
if (temp.next == null){
break;
}
if (temp.next.no > heroNode.no){
break;
}else if (temp.next.no == heroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
System.out.printf("准备插入的编号%d 已经存在,不能加入\n", heroNode.no);
}else {
heroNode.next = temp.next;
heroNode.pre = temp;
temp.next = heroNode;
temp.next.pre = heroNode;
}
}
public void del(int no){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
return;
}
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.printf("要删除的 %d 节点不存在\n", no);
}
}
public void update(HeroNode2 newHeroNode){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
boolean flag = false;
while (true){
if (temp == null){
break;
}
if (temp.no == newHeroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.name = newHeroNode.name;
temp.nickname = newHeroNode.nickname;
}else {
System.out.printf("没有找到 编号 %d 的节点,不能修改\n", newHeroNode.no);
}
}
public void add(HeroNode2 heroNode){
HeroNode2 temp = head;
while(true){
if (temp.next == null){
break;
}
temp = temp.next;
}
temp.next = heroNode;
heroNode.pre = temp;
}
public void list(){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode2 temp = head.next;
while (true){
if (temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
class HeroNode2{
public int no;
public String name;
public String nickname;
public HeroNode2 next;
public HeroNode2 pre;
public HeroNode2(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 + '\'' +
'}';
}
}
约瑟夫问题
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210506210001836.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3Bhbl8wMzEy,size_16,color_FFFFFF,t_70#pic_center)
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.printf("小孩的编号%d \n", curBoy.getNo());
if (curBoy.getNext() == first){
break;
}
curBoy = curBoy.getNext();
}
}
public void countBoy(int startNo, int countNum, int nums){
if (first == null || startNo < 0 || startNo > nums){
System.out.println("参数输入有误,请重新输入");
return;
}
Boy helper = first;
while (true){
if (helper.getNext() == first){
break;
}
helper = helper.getNext();
}
for (int i = 1; i <= startNo -1; i++) {
first = first.getNext();
helper = helper.getNext();
}
while (true){
if (helper == first){
break;
}
for (int i = 1; i <= countNum - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("小孩%d出圈\n", first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后留在圈中的小孩编号%d\n", 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;
}
}