線性結構非線性結構
線性結構(數組、隊列、連結清單、棧):資料元素之前存一一對應關系。
順序存儲結構/順序表(數組):存儲元素位址連續。
鍊式存儲結構(連結清單):存儲元素位址不一定連續。可以充分利用記憶體空間。
非線性結構(二維數組、多元數、廣義表、樹結構、圖結構)。
稀疏sparsearray數組和隊列
應用場景:棋盤、地圖等。
package sparseArray;
public class SparseArray {
/*待完成:
将稀疏數組用IO流儲存到檔案,再重檔案中擷取稀疏數組*/
public static void main(String[] args) {
// 建立一個原始的二維數組11*11
// 0:表示沒有棋子,1:表示 黑子, 2:表示 藍子
int[][] chessMap = new int[11][11];
chessMap[1][2] = 1;
chessMap[2][3] = 2;
chessMap[4][5] = 1;
chessMap[7][9] = 2;
// 列印原數組
for (int[] chessArray : chessMap) {
for (int chess : chessArray) {
System.out.printf("%d\t", chess);
}
System.out.println();
}
// 棋盤中棋子的個數
int sum = 0;
for (int i = 0; i < chessMap.length; i++) {
for (int j = 0; j < chessMap[i].length; j++) {
if (chessMap[i][j] != 0) {
sum++;
}
}
}
// 建立稀疏數組
int count = 0;
int[][] sparseArray = new int[sum + 1][3];
sparseArray[0][0] = chessMap.length;
sparseArray[0][1] = chessMap[0].length;
sparseArray[0][2] = sum;
for (int i = 0; i < chessMap.length; i++) {
for (int j = 0; j < chessMap[i].length; j++) {
if (chessMap[i][j] != 0) {
count++;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chessMap[i][j];
}
}
}
// 列印稀疏數組
for (int[] sparseArr : sparseArray) {
for (int element : sparseArr) {
System.out.printf("%d\t", element);
}
System.out.println();
}
// 将稀疏數組還原
int[][] chessMap2 = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i = 1; i < sparseArray.length; i++) {
chessMap2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
// 列印還原數組
for (int[] chessArray2 : chessMap2) {
for (int chess2 : chessArray2) {
System.out.printf("%d\t", chess2);
}
System.out.println();
}
}
}
隊列
package arrayQueue;
import java.util.Scanner;
public class ArrayQueueDemo {
public static void main(String[] args) {
// 建立一個隊列
ArrayQueue arrayQueue = new ArrayQueue(3);
Scanner input = new Scanner(System.in);
System.out.println("s(show):顯示隊列\na(add):添加資料到隊列\ng(從隊列取出資料)\nh(head):檢視隊列頭的資料\ne(exit):退出程式");
char key = ' ';
while (key != 'e') {
key = input.next().charAt(0);
switch (key) {
case 's':
try {
arrayQueue.showQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'a':
System.out.print("請輸入添加的資料: ");
try {
arrayQueue.addQueue(input.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
System.out.println("取出的資料為" + arrayQueue.getQueue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
System.out.println("隊列頭資料為" + arrayQueue.headQueue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
System.out.println("您已選擇離開");
break;
default:
System.out.println("選擇的選項不存在");
}
}
input.close();
}
}
class ArrayQueue {
private int maxSize;//表示數組的最大容量
private int front;//隊列頭
private int rear;//隊列尾部
private int[] array;//該資料用于存放資料,模拟隊列
// 建立隊列的構造器
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
array = new int[maxSize];
front = -1;//指向隊列頭部,分析出front是指向隊列頭的前一個位置
rear = -1;//指向隊列尾,指向隊列尾的資料(即就是隊列最後一個資料)
}
// 判斷隊列是否滿
public boolean isFull() {
return rear == maxSize - 1;
}
// 判斷隊列是否為空
public boolean isEmpty() {
return front == rear;
}
// 将資料添加到隊列
public void addQueue(int n) {
if (!isFull()) {
array[++rear] = n;
} else {
System.out.println("隊列已滿,添加失敗!");
}
}
// 擷取隊列資料,輸出隊列首元素
public int getQueue() {
// 判斷隊列是否為空
if (!isEmpty()) {
return array[++front];
} else {
throw new RuntimeException("隊列為空,沒有資料可以輸出");
}
}
// 顯示隊列的所有資料
public void showQueue() {
// 周遊
if (!isEmpty()) {
for (int i = 0; i < array.length; i++) {
System.out.printf("array[%d]=%d\n", i, array[i]);
}
} else {
throw new RuntimeException("隊列為空,沒有資料可以周遊");
}
}
// 顯示隊列頭資料
public int headQueue() {
// 判斷
if (!isEmpty()) {
return array[front + 1];
} else {
throw new RuntimeException("隊列為空!");
}
}
}
應用場景:銀行排隊。
環形隊列
package arrayQueue;
import java.util.Scanner;
public class CircleArrayQueueDemo {
public static void main(String[] args) {
// 建立一個隊列
CircleArrayQueue circleArrayQueue = new CircleArrayQueue(4);//說明設定4,其隊列的有效資料最大為3
Scanner input = new Scanner(System.in);
System.out.println("s(show):顯示隊列\na(add):添加資料到隊列\ng(從隊列取出資料)\nh(head):檢視隊列頭的資料\ne(exit):退出程式");
char key = ' ';
while (key != 'e') {
key = input.next().charAt(0);
switch (key) {
case 's':
try {
circleArrayQueue.showQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'a':
System.out.print("請輸入添加的資料: ");
try {
circleArrayQueue.addQueue(input.nextInt());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
System.out.println("取出的資料為" + circleArrayQueue.getQueue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
System.out.println("隊列頭資料為" + circleArrayQueue.headQueue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
System.out.println("您已選擇離開");
break;
default:
System.out.println("選擇的選項不存在");
}
}
}
}
class CircleArrayQueue {
private int maxSize;//表示數組的最大容量
private int front;//front指向隊列的第一個元素,也就是說array[front]就是隊列的第一個元素
// front初始值為0
private int rear;//rear指向隊列的最後一個元素的後一個位置,因為希望空出一個空間作為約定
// rear初始值為0
private int[] array;//該資料用于存放資料,模拟隊列
public CircleArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
array = new int[maxSize];
}
// 判斷隊列是否滿
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
// 判斷資料是否為空
public boolean isEmpty() {
return rear == front;
}
// 添加資料到隊列
public void addQueue(int n) {
if (!isFull()) {
array[rear] = n;
rear = ++rear % maxSize;
} else {
System.out.println("隊列已滿,不能加入資料!");
}
}
// 擷取隊列的資料
public int getQueue() {
if (!isEmpty()) {
int value = array[front];
front = ++front % maxSize;
return value;
} else {
throw new RuntimeException("隊列為空,不能擷取資料!");
}
}
// 顯示隊列的所有資料
public void showQueue() {
// 周遊
if (!isEmpty()) {
for (int i = front; i < front + size(); i++) {
System.out.printf("array[%d]=%d\n", i % maxSize, array[i % maxSize]);
}
} else {
throw new RuntimeException("隊列為空!");
}
}
// 求出目前隊列有效資料的個數
public int size() {
return (rear + maxSize - front) % maxSize;
}
// 顯示目前隊列的首元素
public int headQueue() {
if (!isEmpty()) {
return array[front];
} else {
throw new RuntimeException("隊列為空!");
}
}
}
連結清單
面試題
騰訊面試題:單連結清單反轉
package linkedList;
import java.util.Stack;
public class SingleLinkedListDemo {
public static void main(String[] args) {
// 進行測試
// 先建立節點
HeroNode hero = new HeroNode(1, "宋江", "及時雨");
HeroNode hero1 = new HeroNode(2, "盧俊義", "玉麒麟");
HeroNode hero2 = new HeroNode(3, "吳用", "智多星");
HeroNode hero3 = new HeroNode(4, "林沖", "豹子頭");
// 建立一個連結清單
SingleLinkedList singleLinkedList = new SingleLinkedList();
/*singleLinkedList.add(hero);
singleLinkedList.add(hero1);
singleLinkedList.add(hero2);
singleLinkedList.add(hero3);*/
// 按照順序插入
singleLinkedList.addByOrder(hero3);
singleLinkedList.addByOrder(hero1);
singleLinkedList.addByOrder(hero);
singleLinkedList.addByOrder(hero2);
singleLinkedList.list();
// 修改資訊
/*HeroNode newHeroNode = new HeroNode(4, "老霖", "小包子");
HeroNode newHeroNode2 = new HeroNode(5, "三郎", "拼命三郎");
singleLinkedList.update(newHeroNode);
singleLinkedList.update(newHeroNode2);*/
// 删除節點
/* singleLinkedList.delete(1);
singleLinkedList.delete(4);
singleLinkedList.delete(5);
singleLinkedList.list();*/
// 擷取連結清單有效節點個數
/*System.out.println("有效的節點個數為 "+SingleLinkedList.getLength(singleLinkedList.getHead()));*/
// 擷取連結清單倒數第K個節點
/*System.out.println("倒數第二個節點為 "+SingleLinkedList.findLastIndexNode(singleLinkedList.getHead(),2));*/
// 單連結清單反轉
/*SingleLinkedList.reverseList(singleLinkedList.getHead());
singleLinkedList.list();*/
// 逆序列印連結清單
SingleLinkedList.reversePrint(singleLinkedList.getHead());
}
}
//定義HeroNode,每個HeroNode對象就是一個節點
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 +
'}';
}
}
//定義SingleLinkedList 管理我們的英雄
class SingleLinkedList {
// 先初始化一個頭節點不要動,不存放具體的資料
private HeroNode head = new HeroNode(0, "", "");
public HeroNode getHead() {
return head;
}
// 添加節點到單項連結清單
// 思路,當不考慮編号順序時
// 1.找到目前連結清單的最後節點
// 2.将最後這個節點的next 指向 新的節點
public void add(HeroNode heroNode) {
// 因為head節點不能動,是以我們需要一個輔助的變量temp
HeroNode temp = head;
// 周遊連結清單,找到最後
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
// 當退出while循環時,temp就指向連結清單最後
// 将最後這個節點指向新的節點
temp.next = heroNode;
}
//第二種方式在添加英雄時,根據排名獎英雄插入到指定位置
//(如果單連結清單中已有這個排名,則添加失敗,并給出提示)
public void addByOrder(HeroNode heroNode) {
// 因為頭節點不能動,是以我們仍然通過一個輔助指針(變量)來幫助找到添加的位置
// 是以我們找的temp是位于添加位置的前一個節點,否則插入不了
HeroNode temp = head;
boolean flag = false;//flag标志添加的編号是否存在,預設為false
while (true) {
if (temp.next == null) {//說明temp已經在連結清單的最後
break;
}
if (temp.next.no > heroNode.no) {//位置找到就在temp的後面插入
break;
} else if (temp.next.no == heroNode.no) {//說明希望添加的heroNode的編号已經存在
flag = true;
break;
}
temp = temp.next;//後移,周遊目前連結清單
}
if (flag) {//不能添加,編号已經存在
System.out.printf("準備插入的英雄編号 %d 已經存在,不能添加!\n", heroNode.no);
} else {
//插入到連結清單temp的後面
heroNode.next = temp.next;
temp.next = heroNode;
}
}
//删除節點
//1.head不能動,是以我們需要一個temp輔助節點找到待删除節點的前一個節點
//2.說明我們在比較是,是temp.next.no和要删除的節點的比較
public void delete(int no) {
if (head.next != null) {
HeroNode temp = head;
boolean flag = false;//用于标志要删除的節點是否找到
while (true) {
if (temp.next == null) {//連結清單指針已經到達連結清單最後
break;
}
if (temp.next.no == no) {//找到待删除節點的前一個節點temp
flag = true;
break;
}
temp = temp.next;//temp後移,周遊
}
if (flag) {//進行删除
temp.next = temp.next.next;
} else {
System.out.printf("要删除的 %d 不存在,删除失敗!\n", no);
}
} else {
System.out.println("連結清單為空!");
}
}
//修改節點的資訊,根據no編号來修改,即no編号不能改。
//根據newHeroNode的no來修改即可
public void update(HeroNode newHeroNode) {
if (head.next != null) {
boolean flag = false; //節點是否找到的标志
HeroNode temp = head.next; //定義一個輔助變量
while (true) {
if (temp == null) {//指針已經到達連結清單最後,沒有找到節點
break;
} else 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);
}
} else {
System.out.println("連結清單為空!");
}
}
// 顯示連結清單[周遊]
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 = temp.next;
}
}
// 面試題
//擷取單連結清單有效節點的個數(如果是帶頭節點的連結清單,不統計頭節點)
/**
* @param head 連結清單的頭節點
* @return 傳回有效節點的個數
*/
public static int getLength(HeroNode head) {
int length = 0;
if (head.next != null) {
HeroNode current = head;//定義一個輔助(指針)變量,這裡我們沒有統計頭節點
while (current.next != null) {
length++;
current = current.next;
}
}
return length;
}
// 新浪
//查找單連結清單中的倒數第K個節點
// 1.編寫一個方法,接受head節點,同時接收一個index
// 2.index 表示是倒數第index個節點
// 3.先把連結清單重頭到尾周遊,得到連結清單的總的長度getLength
// 4.得到size後,我們從連結清單的第一個開始周遊(size-index)個,就可以得到
// 5.如果找到了則傳回節點,否則傳回null
public static HeroNode findLastIndexNode(HeroNode head, int index) {
// 判斷如果連結清單為空,傳回null
if (head.next == null) {
return null;
}
// 第一個周遊得到連結清單的長度(節點個數)
int size = getLength(head);
// 第二次周遊 size-index 位置,就是我們倒數的第K個節點
// 先做一個index校驗
if (index <= 0 || index > size) {
return null;
}
// 定義輔助指針(變量)
HeroNode current = head.next;
for (int i = 0; i < size - index; i++) {
current = current.next;
}
return current;
}
// 騰訊
//單連結清單的反轉
public static void reverseList(HeroNode head) {
// 如果目前連結清單為空,或者自由一個節點,無需反轉,直接傳回
if (head.next == null || head.next.next == null) {
return;
}
// 定義一個輔助指針(變量),幫助我們周遊原來的連結清單
HeroNode current = head.next;
HeroNode next = null;//指向目前節點[current]的下一個節點
HeroNode reverseHead = new HeroNode(0, "", "");
// 周遊原來的連結清單,每周遊一個節點,就将其取出并放在新的連結清單reverseHead的最前端
while (current != null) {
next = current.next;//暫時儲存目前節點的下一個節點,因為後面需要使用
current.next = reverseHead.next;//将目前的下一個節點指向新連結清單的最前端
reverseHead.next = current;//将新連結清單reserveHead指向的下一個節點指向剛挂載到新連結清單的節點上
current = next;//讓current後移
}
head.next = reverseHead.next;//将head.next指向reverseHead.next,實作單連結清單反轉
}
// 百度
//反向列印單連結清單内容
// 利用棧這個資料結構,将各個節點壓入棧中,利用棧先進後出的特點逆序列印
public static void reversePrint(HeroNode head) {
if (head.next == null) {//空連結清單,不能列印
return;
}
HeroNode current = head.next;
// 建立一個棧,将連結清單資料壓入
Stack<HeroNode> stack = new Stack<>();
while (current != null) {
stack.push(current);
current = current.next;
}
// 逆序列印
while (!stack.empty()) {
System.out.println(stack.pop());
}
}
}
package linkedList;
public class DoubleLinkedListDemo {
public static void main(String[] args) {
// 進行測試
// 先建立節點
HeroNodeOD heroOD = new HeroNodeOD(1, "宋江", "及時雨");
HeroNodeOD heroOD1 = new HeroNodeOD(2, "盧俊義", "玉麒麟");
HeroNodeOD heroOD2 = new HeroNodeOD(3, "吳用", "智多星");
HeroNodeOD heroOD3 = new HeroNodeOD(4, "林沖", "豹子頭");
// 建立一個連結清單
DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
// 添加
/*doubleLinkedList.add(heroOD);
doubleLinkedList.add(heroOD1);
doubleLinkedList.add(heroOD2);
doubleLinkedList.add(heroOD3);*/
// 按順序添加
doubleLinkedList.addByOrder(heroOD3);
doubleLinkedList.addByOrder(heroOD1);
doubleLinkedList.addByOrder(heroOD);
doubleLinkedList.addByOrder(heroOD2);
// 周遊顯示
doubleLinkedList.list();
// 修改
HeroNodeOD newHeroNode = new HeroNodeOD(4, "劉聰", "一尾魚");
doubleLinkedList.update(newHeroNode);
doubleLinkedList.list();
// 删除
doubleLinkedList.delete(2);
doubleLinkedList.list();
}
}
//定義HeroNodeOD,每個HeroNodeOD對象就是一個節點
class HeroNodeOD {
public int no;
public String name;
public String nickname;
public HeroNodeOD next;//指向下一個節點
public HeroNodeOD prev;//指向前一個節點
// 構造方法
public HeroNodeOD(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 +
'}';
}
}
//定義DoubleLinkedList 管理我們的英雄
class DoubleLinkedList {
// 先初始化一個頭節點不要動,不存放具體的資料
private HeroNodeOD head = new HeroNodeOD(0, "", "");
public HeroNodeOD getHead() {
return head;
}
//添加一個節點到雙向連結清單的最後
public void add(HeroNodeOD newHeroNodeOD) {
// 因為head節點不能動,是以我們需要一個輔助的變量temp
HeroNodeOD temp = head;
// 周遊連結清單,找到最後
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
// 當退出while循環時,temp就指向連結清單最後
temp.next = newHeroNodeOD;
newHeroNodeOD.prev = temp;
}
//第二種方式在添加英雄時,根據排名獎英雄插入到指定位置
//(如果雙向連結清單中已有這個排名,則添加失敗,并給出提示)
public void addByOrder(HeroNodeOD newheroNodeOD) {
// 因為頭結點不能動,是以我們仍然通過一個輔助指針(變量)來幫助找到添加的位置
// 是以我們找的temp是位于添加位置的前一個節點,否則插入不了
HeroNodeOD temp = head;
boolean flag = false;//flag标志添加的編号是否存在,預設為false
while (true) {
if (temp.next == null) {//說明temp已經在連結清單的最後
break;
}
if (temp.next.no > newheroNodeOD.no) {//位置找到就在temp的後面插入
break;
} else if (temp.next.no == newheroNodeOD.no) {//說明希望添加的heroNode的編号已經存在
flag = true;
break;
}
temp = temp.next;//後移,周遊目前連結清單
}
if (flag) {//不能添加,編号已經存在
System.out.printf("準備插入的英雄編号 %d 已經存在,不能添加!\n", newheroNodeOD.no);
} else {
//插入到連結清單temp的後面
newheroNodeOD.next = temp.next;
if (temp.next != null) {
temp.next.prev = newheroNodeOD;
}
temp.next = newheroNodeOD;
newheroNodeOD.prev = temp;
}
}
//從雙向連結清單中删除一個節點
// 1.對于雙向連結清單我們可以直接找到要删除的這個節點
// 2.找到偶,自我即可删除
public void delete(int no) {
if (head.next != null) {
HeroNodeOD temp = head;
boolean flag = false;//用于标志要删除的節點是否找到
while (true) {
if (temp.next == null) {//連結清單指針已經到達連結清單最後
break;
}
if (temp.no == no) {//找到待删除節點
flag = true;
break;
}
temp = temp.next;//temp後移,周遊
}
if (flag) {//進行删除
temp.prev.next = temp.next;
if (temp.next != null) {//避免要删除的節點是雙向連結清單的最後一個而出現空指針現象
temp.next.prev = temp.prev;
}
} else {
System.out.printf("要删除的 %d 不存在,删除失敗!\n", no);
}
} else {
System.out.println("連結清單為空!");
}
}
//修改雙線連結清單中節點的内容(和單項連結清單一樣)
public void update(HeroNodeOD newHeroNodeOD) {
if (head.next != null) {
boolean flag = false; //節點是否找到的标志
HeroNodeOD temp = head.next; //定義一個輔助變量
while (true) {
if (temp == null) {//指針已經到達連結清單最後,沒有找到節點
break;
} else if (temp.no == newHeroNodeOD.no) {//找到要修改的節點
flag = true;
break;
}
temp = temp.next;
}
if (flag) {//更新資訊
temp.name = newHeroNodeOD.name;
temp.nickname = newHeroNodeOD.nickname;
} else {
System.out.printf("沒有找到編号為 %d 的節點,修改失敗!\n", newHeroNodeOD.no);
}
} else {
System.out.println("連結清單為空!");
}
}
//周遊顯示雙線連結清單内容
public void list() {
// 判斷連結清單是否為空
if (head.next == null) {
System.out.println("連結清單為空!");
return;
}
// 因為頭節點不能動,是以我們需要一個輔助變量來周遊
HeroNodeOD temp = head.next;
while (true) {
// 判斷連結清單是否為空
if (temp == null) {
break;
}
// 輸出節點的資訊
System.out.println(temp);
// 将temp後移,此處不後移出現死循環
temp = temp.next;
}
}
}
單項環形連結清單
package linkedList;
public class Josephu {
public static void main(String[] args) {
// 建立單向環形連結清單
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addPerson(125);
circleSingleLinkedList.list();
// 按照規則“出圈”
circleSingleLinkedList.countPerson(10, 20, 125);
}
}
class Person {
private int no;//編号
private Person next;//指向下一個節點,預設null
public Person(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public Person getNext() {
return next;
}
public void setNext(Person next) {
this.next = next;
}
}
//建立一個單向環形連結清單
class CircleSingleLinkedList {
// 建立一個first節點,目前沒有編号
private Person first = null;
//添加小孩節點,構成一個環形連結清單
public void addPerson(int nums) {
// nums做一個資料校驗
if (nums < 1) {
System.out.println("添加個數不能小于1!");
return;
}
Person currentPerson = null;//輔助指針,幫助建構環形連結清單
// 使用for循環建立環形連結清單
for (int i = 1; i <= nums; i++) {
// 根據編号,建立節點
Person person = new Person(i);
// 如果是第一個節點
if (i == 1) {
first = person;
first.setNext(first);//構成環
currentPerson = first;//讓currentPerson指向第一個小孩
} else {
currentPerson.setNext(person);
person.setNext(first);
currentPerson = person;
}
}
}
//周遊目前環形連結清單
public void list() {
// 連結清單是否為空
if (first == null) {
System.out.println("環形連結清單無節點!");
return;
}
// 因為first不能動,是以我們仍然使用一個輔助指針完成周遊
Person currentPerson = first;
while (true) {
System.out.println("編号: " + currentPerson.getNo());
if (currentPerson.getNext() == first) {//說明已經周遊完畢
break;
}
currentPerson = currentPerson.getNext();//currentPerson後移
}
}
//根據使用者的輸入,計算出人出圈的順序
/**
* @param startNo 表示出從第幾個人開始數數
* @param countNum 表示數幾下
* @param nums 表示最初由多少個小孩在圈中
*/
public void countPerson(int startNo, int countNum, int nums) {
// 先對資料進行校驗
if (first == null || startNo < 1 || startNo > nums) {
System.out.println("參數輸入有誤,請重新輸入");
return;
}
// 建立要給輔助指針,幫助完成小孩出圈
Person helper = first;
// 需要建立一個輔助指針(變量)helper,實作應該指向環形連結清單的最後這個節點
while (true) {
if (helper.getNext() == first) {//說明helper指向最後節點
break;
}
helper = helper.getNext();
}
// 報數前,先讓 first 和 helper 移動 k-1 次
for (int i = 0; i < startNo - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
// 當小孩報數時,讓 first 和 helper 指針同時移動 m-1 次,然後出圈
// 循環操作直到圈中隻有一個節點
while (true) {
if (helper == first) {//說明圈中隻有一個節點
break;
}
// 讓 first 和 helper 指針同時移動 countNum-1 次
for (int i = 0; i < countNum - 1; i++) {
first = first.getNext();
helper = helper.getNext();
}
// 這時 first 指向的節點,就是要出圈的節點
System.out.printf("編号: %d 出圈\n", first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.println("圈中剩餘節點的編号: " + first.getNo());
}
}
棧
package stacks;
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
// 建立一個ArrayStack對象 ->表示棧
ArrayStack stack = new ArrayStack(4);
boolean loop = true;
String key = "";
Scanner input = new Scanner(System.in);
System.out.println("push:添加資料到棧(入棧)");
System.out.println("pop:表示從棧取出資料(出棧)");
System.out.println("show:顯示棧");
System.out.println("exit:退出程式");
while (loop) {
key = input.next();
switch (key) {
case "push":
System.out.print("請輸入資料: ");
stack.push(input.nextInt());
break;
case "pop":
System.out.println("出棧的資料是: " + stack.pop());
break;
case "show":
stack.list();
break;
case "exit":
loop = false;
break;
default:
System.out.println("輸入的選項不存在!");
}
}
}
}
//定義一個ArrayStack表示棧
class ArrayStack {
private int maxSize;//棧的大小
private int[] stack;//數組,數組模拟棧,資料就放在該數組
private int top = -1;//top表示棧定,初始化為-1
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
//棧滿
public boolean isFull() {
return top == maxSize - 1;
}
//棧空
public boolean isEmpty() {
return top == -1;
}
//入棧 push
public void push(int value) {
// 先判斷棧是否滿
if (isFull()) {
System.out.println("棧滿,添加失敗");
} else {
stack[++top] = value;
}
}
//出棧 pop 将棧頂資料傳回
public int pop() {
// 先判斷棧是否為空
if (isEmpty()) {
throw new RuntimeException("棧空,無資料可傳回");
} else {
int value = stack[top--];
return value;
}
}
//顯示棧的情況[周遊棧],周遊是,需要從棧頂開始顯示資料
public void list() {
if (isEmpty()) {
System.out.println("棧空,無資料可以周遊");
}
// 需要從棧頂顯示資料
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
希爾排序
希爾排序【交換式/位移式】算法實作
package insertionSorting;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class ShellSort {
public static void main(String[] args) {
// 建立含有80000個整型的随機數組
int[] arr = new int[80000];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 800000);
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = simpleDateFormat.format(date);
System.out.println("排序前的時間: " + dateStr);
// shellSort(arr);
shellSort1(arr);
Date date1 = new Date();
dateStr = simpleDateFormat.format(date1);
System.out.println("排序後的時間: " + dateStr);
// int[] arr = {8,9,1,7,2,3,5,4,6,0};
}
/*
// 使用逐漸推導的方式來編寫希爾排序
// 希爾排序時,對有序序列在插入時采用交換法
// 思路(算法)===> 代碼
private static void shellSort(int[] arr) {
int temp = 0;
int count = 0;
// 根據前面的逐漸分析,使用循環處理
for (int gap = arr.length / 2; gap > 0; gap /=2){
for (int i = gap; i < arr.length; i++){
// 周遊各組中的所有元素(共gap組,每組有arr.length/gap個元素),步長gap
for (int j = i - gap; j >= 0; j -= gap){
// 如果目前元素大于加上步長後的那個元素,說明交換
if (arr[j] > arr[j + gap]){
temp = arr[j];
arr[j] = arr[j + gap];
arr[j + gap] = temp;
}
}
}
// System.out.println("希爾排序第"+ (++count) + "輪=" + Arrays.toString(arr));
}
}
*/
//對交換式的希爾排序進行優化 -> 位移法
private static void shellSort1(int[] arr) {
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
// 從第gap個元素,逐個對其所在的組進行直接插入排序
for (int i = gap; i < arr.length; i++) {
int j = i;
int temp = arr[j];
if (arr[j] < arr[j - gap]) {
while (j - gap >= 0 && temp < arr[j - gap]) {
// 移動
arr[j] = arr[j - gap];
j -= gap;
}
// 當退出while後,就給temp找到插入的位置
arr[j] = temp;
}
}
}
}
}