1.链表
t02单链表的基本操作
import org.junit.Test;
import java.util.Scanner;
public class t02单链表的基本操作 {
Scanner scanner = new Scanner(System.in);
@Test
public void ss() {
System.out.println("请输入你要选择的功能");
System.out.println("1:头插法创建");
System.out.println("2:尾插法法创建");
System.out.println("3:打印链表");
System.out.println("4:添加链表");
System.out.println("5:删除节点");
System.out.print("6:修改节点");
int select = scanner.nextInt();
Node head = new Node();
while (select !=0){
switch (select){
case 1:
head = createHead();
print(head);
break;
case 2:
head = createTail();
print(head);
break;
case 3:
print(head);
break;
case 4:
head = insert(head);
print(head);
break;
case 5:
head = delete(head);
print(head);
break;
case 6:
update(head);
print(head);
break;
}
System.out.print("请输入你要选择的功能:");
select = scanner.nextInt();
}
System.out.println("退出了……");
}
private Node createHead(){
Node head = new Node(),tempNode;
int x;
tempNode = head;
System.out.print("创造节点,请输入:");
while ((x = scanner.nextInt()) != -1){
Node node = new Node(x);
tempNode.next = node;
tempNode = node;
System.out.print("请继续输入:");
}
return head.next;
}
private Node createTail(){
Node head = null;
int x;
System.out.print("创造节点,请输入:");
while ((x = scanner.nextInt()) != -1){
Node node = new Node(x);
node.next = head;
head = node;
System.out.print("请继续输入:");
}
return head;
}
private void print(Node head){
while (head != null){
System.out.println(head.value);
head = head.next;
}
}
private int getLength(Node head){
int length = 0;
while (head != null){
length++;
head = head.next;
}
return length;
}
private Node insert(Node head){
System.out.print("请输入位置");
int pos = scanner.nextInt();
System.out.print("请输入值");
int value = scanner.nextInt();
Node pre = head;
for (int i = 1; i < pos-1; i++) {
pre = pre.next;
}
Node node = new Node(value);
if (pos == 1){
node.next = head;
head = node;
}else if (pos > getLength(head)+1){
System.out.println("输入有误!!请重新输入!");
head = insert(head);
}
else {
node.next = pre.next;
pre.next = node;
}
return head;
}
private Node delete(Node head){
System.out.println("请输入要删除的位置:");
int pos = scanner.nextInt();
if (pos < 1 || pos > getLength(head)){
System.out.println("输出错误,请重新输入");
delete(head);
}
Node pre = head;
for (int i = 1; i < pos-1; i++) {
pre = pre.next;
}
if (pos == 1){
return head.next;
}else if (pos == getLength(head)){
pre.next = null;
} else {
pre.next = pre.next.next;
}
return head;
}
private Node update(Node head){
System.out.print("请输入要修改的位置:");
int pos = scanner.nextInt();
if (pos < 1 || pos > getLength(head)){
System.out.print("输出错误,请重新输入");
update(head);
}
System.out.print("请输入要修改的值:");
int value = scanner.nextInt();
Node cur = head;
for (int i = 1; i < pos; i++) {
cur = cur.next;
}
cur.value = value;
return head;
}
class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
public Node() {
}
}
}
t04双向链表的基本操作
import org.junit.Test;
import java.util.Scanner;
import static java.lang.reflect.Array.getLength;
public class t04双向链表的基本操作 {
private class Node {
int value;
Node next;
Node pre;
public Node(int value) {
this.value = value;
}
public Node() {
}
}
Scanner scanner = new Scanner(System.in);
@Test
public void test(){
System.out.println("请输入你要选择的功能");
System.out.println("1:创建");
System.out.println("2:打印链表");
System.out.println("3:添加链表");
System.out.println("4:删除节点");
System.out.print("5:修改节点");
int select = scanner.nextInt();
Node head = new Node();
while (select !=0){
switch (select){
case 1:
head = create();
print(head);
break;
case 2:
print(head);
break;
case 3:
head = insert(head);
print(head);
break;
case 4:
head = delete(head);
print(head);
break;
case 5:
head = update(head);
print(head);
break;
}
System.out.print("请输入你要选择的功能:");
select = scanner.nextInt();
}
System.out.println("退出了……");
}
private Node update(Node head) {
System.out.print("指定位置:");
int pos = scanner.nextInt();
if (pos < 1 || pos > getLength(head)){
System.out.println("位置不对路……请重新输入");
update(head);
}else {
System.out.print("指定值:");
int value = scanner.nextInt();
Node cur = head;
for (int i = 1; i < pos; i++) {
cur = cur.next;
}
cur.value = value;
}
return head;
}
private Node delete(Node head) {
System.out.print("指定位置:");
int pos = scanner.nextInt();
if (pos < 1 || pos > getLength(head)){
System.out.println("位置不对路……请重新输入");
delete(head);
}else {
if (pos == 1){
return head.next;
}
Node cur = head;
for (int i = 1; i < pos; i++) {
cur = cur.next;
}
cur.pre.next = cur.next;
if (cur.next != null){
cur.next.pre = cur.pre;
}
}
return head;
}
private Node insert(Node head) {
System.out.print("指定位置:");
int pos = scanner.nextInt();
if (pos < 1 || pos > getLength(head)){
System.out.println("位置不对路……请重新输入");
insert(head);
}else {
System.out.print("指定值:");
int value = scanner.nextInt();
Node node = new Node(value);
if (pos == 1){
node.next = head;
head.pre = node;
head = node;
}else {
Node pre = head;
for (int i = 1; i < pos-1; i++) {
pre = pre.next;
}
node.next = pre.next;
pre.next = node;
node.pre = pre;
}
}
return head;
}
private int getLength(Node head){
int length = 0;
while (head != null){
length++;
head = head.next;
}
return length;
}
private Node create(){
int value;
Node head = new Node(),cur = null;
System.out.print("请输入值:");
int flag = 1;
while ((value = scanner.nextInt()) != -1){
if (flag == 1){
head.value = value;
cur = head;
flag = 0;
}else {
Node node = new Node(value);
cur.next = node;
node.pre = cur;
cur = node;
}
System.out.print("请继续输入:");
}
return head;
}
private void print(Node head){
while (head != null){
System.out.println(head.value);
head = head.next;
}
}
}
t06循环链表的基本操作
import org.junit.Test;
import java.util.Scanner;
public class t06循环链表的基本操作 {
private class Node {
int value;
Node next;
Node pre;
public Node(int value) {
this.value = value;
}
public Node() {
}
}
Scanner scanner = new Scanner(System.in);
@Test
public void main() {
System.out.println("请输入你要选择的功能");
System.out.println("1:创建");
System.out.println("2:打印链表");
System.out.println("3:添加链表");
System.out.println("4:删除节点");
System.out.print("5:修改节点");
int select = scanner.nextInt();
Node head = new Node();
while (select != 0) {
switch (select) {
case 1:
head = create();
print(head);
break;
case 2:
print(head);
break;
case 3:
head = insert(head);
print(head);
break;
case 4:
head = delete(head);
print(head);
break;
case 5:
head = update(head);
print(head);
break;
}
System.out.print("请输入你要选择的功能:");
select = scanner.nextInt();
}
System.out.println("退出了……");
}
private Node update(Node head) {
System.out.print("指定位置:");
int pos = scanner.nextInt();
if (pos < 1 || pos > getLength(head)){
System.out.println("位置不对路……请重新输入");
update(head);
}else {
System.out.print("指定值:");
int value = scanner.nextInt();
Node cur = head;
for (int i = 1; i < pos; i++) {
cur = cur.next;
}
cur.value = value;
}
return head;
}
private Node delete(Node head) {
System.out.print("指定位置:");
int pos = scanner.nextInt();
if (pos < 1 || pos > getLength(head)){
System.out.println("位置不对路……请重新输入");
delete(head);
}else {
Node cur = head.next;
if (pos == 1){
head.pre.next = cur;
return cur;
}
cur = head;
for (int i = 1; i < pos; i++) {
cur = cur.next;
}
cur.pre.next = cur.next;
cur.next.pre = cur.pre;
}
return head;
}
private Node insert(Node head) {
System.out.print("指定位置:");
int pos = scanner.nextInt();
if (pos < 1 || pos > getLength(head)) {
System.out.println("位置不对路……请重新输入");
insert(head);
} else {
System.out.print("指定值:");
int value = scanner.nextInt();
Node node = new Node(value);
if (pos == 1) {
node.next = head;
node.pre = head.pre;
head.pre.next = node;
head.pre = node;
head = node;
} else {
Node pre = head;
for (int i = 1; i < pos - 1; i++) {
pre = pre.next;
}
node.next = pre.next;
pre.next = node;
node.pre = pre;
}
}
return head;
}
private Node create() {
System.out.print("请输入值:");
Node head = new Node();
Node pre = head;
int value = 0;
int flag = 0;
while ((value = scanner.nextInt()) != -1) {
if (flag == 0) {
head.value = value;
head.next = head;
head.pre = head;
flag++;
} else {
Node node = new Node();
node.value = value;
pre.next = node;
node.pre = pre;
node.next = head;
pre = node;
head.pre = node;
}
System.out.print("请继续输入值:");
}
return head;
}
private void print(Node head) {
Node cur = head;
while (cur.next != head) {
System.out.println(cur.value);
cur = cur.next;
}
System.out.println(cur.value);
}
private int getLength(Node head) {
int length = 0;
Node cur = head;
while (cur.next != head) {
cur = cur.next;
length++;
}
return ++length;
}
}
2.栈
t01链表栈
private class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public Node() {
}
}
private class Stack {
Node top;
int count;
int size = 5;
public Stack() {
}
public void pull(int value) {
if (isFull()) {
throw new RuntimeException("栈满了");
}
top = new Node(value, top);
this.count++;
}
public boolean isFull() {
if (this.count == this.size) {
return true;
} else {
return false;
}
}
public boolean isEmpy() {
if (this.count == 0) {
return true;
} else {
return false;
}
}
public int push() {
if (isEmpy()) {
throw new RuntimeException("栈为空");
}
int value = this.top.value;
this.top = this.top.next;
this.count--;
return value;
}
public int peek() {
if (isEmpy()) {
throw new RuntimeException("栈为空");
}
int value = this.top.value;
return value;
}
public void print(){
if (isEmpy()) System.out.println("无");
else {
while (!isEmpy()){
System.out.println(this.push());
}
}
}
}
@Test
public void test() {
Stack stack = new Stack();
stack.pull(1);
stack.pull(2);
stack.pull(3);
stack.pull(4);
stack.pull(5);
stack.pull(6);
stack.print();
}
t02数组栈
private class Stack{
private int[] arr;
private int size = 5;
private int count;
public Stack(){
this.arr = new int[size];
this.count = -1;
}
public boolean isFull(){
if (this.count == this.size-1) return true;
else return false;
}
public boolean isEmpty(){
if (count == -1) return true;
else return false;
}
public void push(int value){
if (isFull()) throw new RuntimeException("栈满了");
arr[++count] = value;
}
public int pull(){
if (isEmpty()) throw new RuntimeException("空");
return arr[count--];
}
public int peek(){
if (isEmpty()) throw new RuntimeException("空");
return arr[count];
}
public void print(){
if (isEmpty()) System.out.println("无");
else {
while (!isEmpty()) System.out.println(pull());;
}
}
}
@Test
public void test(){
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.print();
}
3.队列
t01链表队列的实现
private class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public Node() {
}
}
private class Queue{
Node tail;
Node head;
int size = 5;
int count = 0;
private boolean isEmpty(){
if (this.head == null) return true;
else return false;
}
private boolean isFull(){
if (size == count) return true;
else return false;
}
private void push(int value) {
if (head == null){
head = new Node(value);
tail = head;
}else {
if (isFull()) throw new RuntimeException("队列满");
else {
Node temp = new Node(value);
tail.next = temp;
tail = temp;
}
}
count++;
}
private int pull(){
if (isEmpty()) throw new RuntimeException("队列空");
int value = head.value;
head = head.next;
count--;
return value;
}
private int peek(){
if (isEmpty()) throw new RuntimeException("队列空");
int value = head.value;
return value;
}
private void print(){
while (this.head != null){
System.out.println(pull());
}
}
}
@Test
public void test(){
Queue queue = new Queue();
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
queue.pull();
queue.push(6);
queue.print();
}
t02数组队列的实现
private class Queue{
private int size = 5;
private int count = 0;
private int head = -1;
private int tail = -1;
int[] arr;
public Queue(){
arr = new int[size];
}
private boolean isEmpty(){
if (this.count == 0) return true;
else return false;
}
private boolean isFull(){
if (head == tail && head !=-1) return true;
else return false;
}
private void pull(int value){
if (isFull()) throw new RuntimeException("队列满");
else {
tail = (tail+1)%size;
arr[tail] = value;
count++;
}
}
private int push(){
if (isEmpty()) throw new RuntimeException("队列空");
else {
head = (head+1)%size;
int value = arr[head];
count--;
return value;
}
}
private int peek(){
if (isEmpty()) throw new RuntimeException("队列空");
return arr[count];
}
private void print(){
if (isEmpty()) throw new RuntimeException("队列空");
while (!isEmpty()){
System.out.println(push());
}
}
}
@Test
public void test(){
Queue queue = new Queue();
queue.pull(1);
queue.pull(2);
queue.pull(3);
queue.pull(4);
queue.pull(5);
queue.push();
queue.pull(6);
queue.print();
}
3.树
T01二叉树
import org.junit.Test;
import java.util.*;
public class T01二叉树 {
private class Node {
private int value;
private Node left;
private Node right;
public Node(int value) {
this.value = value;
}
public Node() {
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
private class BinaryTree {
private Node root;
private void clear(Node node) {
if (node != null) {
clear(node.left);
clear(node.right);
node = null;
}
}
private boolean isEmpty() {
return root == null;
}
private int getHeight(Node node) {
if (node == null) {
return 0;
} else {
int l = getHeight(root.left);
int r = getHeight(root.right);
return l > r ? (l + 1) : (r + 1);
}
}
private int getHeight() {
return getHeight(root);
}
private int getSize(Node node) {
if (node == null) {
return 0;
} else {
return getSize(node.left) + getSize(node.right) + 1;
}
}
private int getSize() {
return getSize(root);
}
private Node getParent(Node pre, Node node) {
if (pre == null) return null;
if (pre.left == node || pre.right == node) return pre;
Node temp = null;
if (getParent(pre.left, node) != null) {
temp = getParent(pre.left, node);
return temp;
} else {
return getParent(pre.right, node);
}
}
private void insertLeft(Node parent, Node node) {
parent.setLeft(node);
}
private void insertRight(Node parent, Node node) {
parent.setRight(node);
}
private void preOrder(Node node) {
if (node != null) {
System.out.println("/" + node.value + "\\");
preOrder(node.left);
preOrder(node.right);
}
}
private void preOrder() {
preOrder(root);
}
private void centerOrder() {
centerOrder(root);
}
private void postOrder() {
postOrder(root);
}
private void centerOrder(Node node) {
if (node != null) {
centerOrder(node.left);
System.out.println(node.value);
centerOrder(node.right);
}
}
private void postOrder(Node node) {
if (node != null) {
centerOrder(node.left);
centerOrder(node.right);
System.out.println(node.value);
}
}
private void insert(int value) {
Node node = new Node(value);
if (root == null) {
root = node;
} else {
Node temp = this.root;
while (temp != null) {
if (value < temp.value) {
if (temp.left == null) {
temp.left = node;
return;
} else {
temp = temp.left;
}
} else {
if (temp.right == null) {
temp.right = node;
return;
} else {
temp = temp.right;
}
}
}
}
}
private void insert2(int value) {
Node node = new Node(value);
if (root == null) {
root = node;
} else {
Node temp = this.root;
while (temp != null) {
if (temp.left == null) {
temp.left = node;
return;
} else if (temp.right == null) {
temp.right = node;
return;
} else if (temp.left.left == null || temp.left.right == null) {
temp = temp.left;
} else if (temp.right.left == null || temp.right.right == null) {
temp = temp.right;
}
}
}
}
}
private ArrayList<Integer> dfs(Node root) {
ArrayList<Integer> lists = new ArrayList<>();
if (root == null) return lists;
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node pop = stack.pop();
if (pop.right != null)
stack.push(pop.right);
if (pop.left != null)
stack.push(pop.left);
lists.add(pop.value);
}
return lists;
}
private ArrayList<Integer> bfs(Node node){
ArrayList<Integer> lists = new ArrayList<>();
if (node == null) return lists;
LinkedList<Node> queue = new LinkedList<>();
queue.offer(node);
while (!queue.isEmpty()){
Node poll = queue.poll();
if (poll.left != null) queue.offer(poll.left);
if (poll.right != null) queue.offer(poll.right);
lists.add(poll.value);
}
return lists;
}
@Test
public void test() {
BinaryTree binaryTree = new BinaryTree();
binaryTree.insert2(10);
binaryTree.insert2(12);
binaryTree.insert2(2);
binaryTree.insert2(3);
binaryTree.insert2(5);
ArrayList<Integer> bfs = bfs(binaryTree.root);
System.out.println(bfs.toString());
}
}
4.图
T01图的存储
public class T01图的存储 {
private class MatrixUDG {
private char[] mVexs;
private int[][] mMatrix;
public MatrixUDG() {
System.out.printf("input vertex number: ");
int vlen = readInt();
System.out.printf("input edge number: ");
int elen = readInt();
if (vlen < 1 || elen < 1 || (elen > (vlen * (vlen - 1)))) {
System.out.printf("input error: invalid parameters!\n");
return;
}
mVexs = new char[vlen];
for (int i = 0; i < mVexs.length; i++) {
System.out.printf("vertex(%d): ", i);
mVexs[i] = readChar();
}
mMatrix = new int[vlen][vlen];
for (int i = 0; i < elen; i++) {
System.out.printf("edge(%d):", i);
char c1 = readChar();
char c2 = readChar();
int p1 = getPosition(c1);
int p2 = getPosition(c2);
if (p1 == -1 || p2 == -1) {
System.out.printf("input error: invalid edge!\n");
return;
}
mMatrix[p1][p2] = 1;
mMatrix[p2][p1] = 1;
}
}
public MatrixUDG(char[] vexs, char[][] edges) {
int vlen = vexs.length;
int elen = edges.length;
mVexs = new char[vlen];
for (int i = 0; i < mVexs.length; i++)
mVexs[i] = vexs[i];
mMatrix = new int[vlen][vlen];
for (int i = 0; i < elen; i++) {
int p1 = getPosition(edges[i][0]);
int p2 = getPosition(edges[i][1]);
mMatrix[p1][p2] = 1;
mMatrix[p2][p1] = 1;
}
}
private int getPosition(char ch) {
for (int i = 0; i < mVexs.length; i++)
if (mVexs[i] == ch)
return i;
return -1;
}
private char readChar() {
char ch = '0';
do {
try {
ch = (char) System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
} while (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')));
return ch;
}
private int readInt() {
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
public void print() {
System.out.printf("Martix Graph:\n");
for (int i = 0; i < mVexs.length; i++) {
for (int j = 0; j < mVexs.length; j++)
System.out.printf("%d ", mMatrix[i][j]);
System.out.printf("\n");
}
}
}
@Test
public void test01() {
char[] vexs = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
char[][] edges = new char[][]{
{'A', 'C'},
{'A', 'D'},
{'A', 'F'},
{'B', 'C'},
{'C', 'D'},
{'E', 'G'},
{'F', 'G'}};
MatrixUDG pG;
pG = new MatrixUDG(vexs, edges);
pG.print();
}
@Test
public void test02() {
MatrixUDG matrixUDG = new MatrixUDG();
matrixUDG.print();
}
@Test
public void test03() {
int x, y;
int v, e;
Scanner scanner = new Scanner(System.in);
System.out.print("顶点数:");
v = scanner.nextInt();
System.out.print("边数:");
e = scanner.nextInt();
int[][] arr = new int[v][v];
for (int i = 0; i < e; i++) {
System.out.print("边端点x(" + i + ")");
x = scanner.nextInt();
System.out.print("边端点y(" + i + ")");
y = scanner.nextInt();
arr[x - 1][y - 1] = 1;
arr[y - 1][x - 1] = 1;
}
System.out.println();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
private class Edge {
private int v;
private int w;
public Edge(int v, int w) {
this.v = v;
this.w = w;
}
public int from() {
return v;
}
public int to() {
return w;
}
@Override
public String toString() {
return String.format("%d->%d", v, w);
}
}
private class EdgeWeightDigraph {
public int v;
public int e;
public ArrayList<Edge>[] adj;
public EdgeWeightDigraph(int v) {
this.v = v;
this.e = e;
adj = new ArrayList[v];
for (int i = 0; i < v; i++) {
adj[i] = new ArrayList<Edge>();
}
}
public void addEdge(Edge e) {
adj[e.from()].add(e);
this.e++;
}
public void addEdge2(Edge e) {
adj[e.from()].add(e);
int from = e.from();
int to = e.to();
Edge edge = new Edge(to, from);
adj[edge.from()].add(edge);
this.e++;
}
public void printEdge() {
for (int i = 0; i < v; i++) {
for (int j = 0; j < adj[i].size(); j++) {
Edge e = adj[i].get(j);
if (j == 0) System.out.print(e);
else System.out.print("->" + e.to());
}
System.out.println();
}
}
public void printEdge2() {
for (int i = 0; i < v; i++) {
for (int j = 0; j < adj[i].size(); j++) {
Edge e = adj[i].get(j);
if (j == 0) System.out.print(e);
else System.out.print("->" + e.to());
}
System.out.println();
}
}
}
@Test
public void test04() {
EdgeWeightDigraph graph = new EdgeWeightDigraph(5);
Edge e = new Edge(0, 1);
Edge e1 = new Edge(0, 2);
Edge e11 = new Edge(0, 3);
Edge e2 = new Edge(1, 2);
Edge e3 = new Edge(2, 3);
Edge e4 = new Edge(3, 4);
graph.addEdge2(e);
graph.addEdge2(e1);
graph.addEdge2(e11);
graph.addEdge2(e2);
graph.addEdge2(e3);
graph.addEdge2(e4);
graph.printEdge();
}
private class ChainForwardStar {
private Edge[] edges;
private int cnt = 0;
private int[] head;
private class Edge {
int to;
int w;
int next;
}
public void add(int u, int v, int w) {
edges[cnt] = new Edge();
edges[cnt].to = v;
edges[cnt].w = w;
edges[cnt].next = head[u];
head[u] = cnt;
cnt++;
}
public void bfs(int node_num) {
boolean[] visited = new boolean[node_num + 1];
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
while (!queue.isEmpty()) {
int u = queue.poll();
System.out.print(u + " ");
for (int i = head[u]; i != -1; i = edges[i].next) {
int f = edges[i].to;
if (!visited[f]) {
queue.offer(f);
visited[f] = true;
}
}
}
}
}
@Test
public void test05() {
ChainForwardStar cc = new ChainForwardStar();
Scanner scanner = new Scanner(System.in);
System.out.print("请输入节点个数:");
int node_num = scanner.nextInt();
cc.head = new int[node_num + 1];
for (int i = 0; i < cc.head.length; i++) {
cc.head[i] = -1;
}
System.out.print("请输入边的数量:");
int edge_num = scanner.nextInt();
cc.edges = new ChainForwardStar.Edge[edge_num];
System.out.print("请输入所有边,及他们的权重:格式: from to weight:(回车下一行开始)");
scanner.nextLine();
scanner.nextLine();
for (int i = 0; i < edge_num; i++) {
String line = scanner.nextLine();
String[] values = line.split(" ");
int u = Integer.valueOf(values[0]);
int v = Integer.valueOf(values[1]);
int w = Integer.valueOf(values[2]);
cc.add(u, v, w);
}
System.out.print("请输入想要遍历的结点:");
int node = scanner.nextInt();
int count = 1;
for (int u = cc.head[node]; u != -1; u = cc.edges[u].next) {
System.out.println(node+"结点连接的第" + count + "条边的去往结点->" + cc.edges[u].to);
System.out.println(node+"结点连接的第" + count + "条边的的权重" + cc.edges[u].w);
if (u == -1) {
break;
}
count++;
System.out.println(node + "号结点上出发的下一条边的下标:" + cc.edges[u].next);
}
cc.bfs(node_num);
}
}
T02图的遍历
public class T02遍历 {
private class BFSTest {
private Queue<Vertex> queue;
private int[][] edges;
private Vertex[] vertices;
private int size;
public BFSTest(Vertex[] vertices, int[][] edges) {
queue = new LinkedList<>();
this.size = vertices.length;
this.vertices = vertices;
this.edges = edges;
}
public BFSTest() {
}
public void BFS() {
queue.offer(vertices[0]);
vertices[0].wasVisited = true;
while (!queue.isEmpty()) {
Vertex item = queue.poll();
System.out.println(item);
int index = 0;
if (item != null) {
index = item.index;
}
for (int i = 0; i < size; i++) {
if ((edges[index][i] != 0) && (vertices[i].wasVisited == false)) {
queue.offer(vertices[i]);
vertices[i].wasVisited = true;
}
}
}
}
private class Vertex {
private char vertex;
private int index;
private boolean wasVisited;
public Vertex(char vertex, int index) {
this.vertex = vertex;
this.index = index;
wasVisited = false;
}
@Override
public String toString() {
return "Vertex{" +
"vertex=" + vertex +
'}';
}
}
}
@Test
public void test01() {
BFSTest bfsTest = new BFSTest();
BFSTest.Vertex[] V = {
bfsTest.new Vertex('0', 0),
bfsTest.new Vertex('1', 1),
bfsTest.new Vertex('2', 2),
bfsTest.new Vertex('3', 3),
bfsTest.new Vertex('4', 4),
bfsTest.new Vertex('5', 5),
bfsTest.new Vertex('6', 6),
bfsTest.new Vertex('7', 7),
bfsTest.new Vertex('8', 8)
};
int[][] edges = {
{0, 1, 1, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
};
BFSTest b = new BFSTest(V, edges);
b.BFS();
}
private class DFSTest {
private Stack<Vertex> stack;
private int[][] edges;
private Vertex[] vertices;
private int size;
public DFSTest(Vertex[] vertices, int[][] edges){
stack=new Stack<>();
this.size=vertices.length;
this.vertices=vertices;
this.edges=edges;
}
public DFSTest(){}
public void DFS(){
System.out.println(vertices[0]);
stack.push(vertices[0]);
vertices[0].wasVisited=true;
Vertex item;
int row;
int column=0;
while (!stack.isEmpty()){
item=stack.peek();
row=item.index;
column=isExistAdjacentPoint(row,column);
if(column == -1){
stack.pop();
column=row+1;
}else {
System.out.println(vertices[column]);
vertices[column].wasVisited=true;
stack.push(vertices[column]);
column=0;
}
}
}
private int isExistAdjacentPoint(int row, int column) {
for(int i=column;i<size;i++){
if((edges[row][i] !=0) && (vertices[i].wasVisited==false)){
return i;
}
}
return -1;
}
private class Vertex{
private char vertex;
private int index;
private boolean wasVisited;
public Vertex(char vertex,int index){
this.vertex = vertex;
this.index=index;
wasVisited = false;
}
@Override
public String toString() {
return "Vertex{" +
"vertex=" + vertex +
'}';
}
}
}
@Test
public void main(String[] args){
DFSTest dfsTest = new DFSTest();
DFSTest.Vertex[] V={
dfsTest.new Vertex('0',0),
dfsTest.new Vertex('1',1),
dfsTest.new Vertex('2',2),
dfsTest.new Vertex('3',3),
dfsTest.new Vertex('4',4),
dfsTest.new Vertex('5',5),
dfsTest.new Vertex('6',6),
dfsTest.new Vertex('7',7),
dfsTest.new Vertex('8',8)
};
int[][] edges={
{0,1,1,0,0,0,0,0,0},
{0,0,0,1,1,0,0,0,0},
{0,0,0,0,1,1,1,0,0},
{0,0,0,0,1,0,0,0,0},
{0,1,0,0,0,0,0,1,0},
{0,0,0,0,0,0,1,0,0},
{0,0,1,0,0,0,0,0,1},
{0,0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,0,0},
};
DFSTest b=new DFSTest(V,edges);
b.DFS();
}
}
T03最小生成树
public class T03最小生成树 {
private class MinSpanTree {
int[][] matrix;
int MAX_WEIGHT = Integer.MAX_VALUE;
int size;
public void prim() {
int[] closeWeight = new int[size];
int minWeight;
int minId;
int sum = 0;
for (int i = 0; i < size; i++) {
closeWeight[i] = matrix[0][i];
}
System.out.println("从顶点v0开始查找");
for (int i = 0; i < size - 1; i++) {
minWeight = MAX_WEIGHT;
minId = 0;
for (int j = 0; j < size; j++) {
if (closeWeight[j] > 0 && closeWeight[j] < minWeight) {
minWeight = closeWeight[j];
minId = j;
}
}
System.out.println("找到顶点:v" + minId + " 权值为:" + minWeight);
sum += minWeight;
closeWeight[minId] = 0;
for (int j = 0; j < size; j++) {
if (closeWeight[j] != 0 && matrix[minId][j] < closeWeight[j]) {
closeWeight[j] = matrix[minId][j];
}
}
}
System.out.println("最小权值总和为:" + sum);
}
private void createGraph(int index) {
size = index;
matrix = new int[index][index];
int[] v0 = {0, 10, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 11, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT};
int[] v1 = {10, 0, 18, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 16, MAX_WEIGHT, 12};
int[] v2 = {MAX_WEIGHT, 18, 0, 22, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 8};
int[] v3 = {MAX_WEIGHT, MAX_WEIGHT, 22, 0, 20, MAX_WEIGHT, MAX_WEIGHT, 16, 21};
int[] v4 = {MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 20, 0, 26, MAX_WEIGHT, 7, MAX_WEIGHT};
int[] v5 = {11, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 26, 0, 17, MAX_WEIGHT, MAX_WEIGHT};
int[] v6 = {MAX_WEIGHT, 16, MAX_WEIGHT, 24, MAX_WEIGHT, 17, 0, 19, MAX_WEIGHT};
int[] v7 = {MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 16, 7, MAX_WEIGHT, 19, 0, MAX_WEIGHT};
int[] v8 = {MAX_WEIGHT, 12, 8, 21, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 0};
matrix[0] = v0;
matrix[1] = v1;
matrix[2] = v2;
matrix[3] = v3;
matrix[4] = v4;
matrix[5] = v5;
matrix[6] = v6;
matrix[7] = v7;
matrix[8] = v8;
}
}
@Test
public void test01() {
MinSpanTree graph = new MinSpanTree();
graph.createGraph(9);
graph.prim();
}
final int INF = Integer.MAX_VALUE;
private class KruskalAlgorithm {
int edgeNum;
char[] vertexs;
int[][] matrix;
public KruskalAlgorithm(char[] vertexs, int[][] matrix) {
this.vertexs = new char[vertexs.length];
for (int i = 0; i < vertexs.length; i++) {
this.vertexs[i] = vertexs[i];
}
this.matrix = new int[vertexs.length][vertexs.length];
for (int i = 0; i < vertexs.length; i++) {
for (int j = 0; j < vertexs.length; j++) {
this.matrix[i][j] = matrix[i][j];
}
}
for (int i = 0; i < vertexs.length; i++) {
for (int j = i + 1; j < vertexs.length; j++) {
if (this.matrix[i][j] != INF) {
edgeNum++;
}
}
}
}
public void print() {
for (int i = 0; i < vertexs.length; i++) {
for (int j = 0; j < vertexs.length; j++) {
System.out.printf("%12d", matrix[i][j]);
}
System.out.println();
}
}
public void sortEdges(KData[] edges) {
for (int i = 0; i < edges.length - 1; i++) {
for (int j = 0; j < edges.length - 1 - i; j++) {
if (edges[j].weight > edges[j + 1].weight) {
KData temp = edges[j];
edges[j] = edges[j + 1];
edges[j + 1] = temp;
}
}
}
}
public int getPosition(char c) {
for (int i = 0; i < vertexs.length; i++) {
if (vertexs[i] == c) {
return i;
}
}
return -1;
}
public KData[] getEdges() {
int index = 0;
KData[] edges = new KData[edgeNum];
for (int i = 0; i < vertexs.length; i++) {
for (int j = i + 1; j < vertexs.length; j++) {
if (matrix[i][j] != INF) {
edges[index++] = new KData(vertexs[i], vertexs[j], matrix[i][j]);
}
}
}
return edges;
}
private int getEnd(int[] parent, int i) {
while (parent[i] != 0) {
i = parent[i];
}
return i;
}
public void kruskal() {
int index = 0;
int[] parent = new int[edgeNum];
KData[] rets = new KData[edgeNum];
KData[] edges = getEdges();
System.out.println("图的边的集合=" + Arrays.toString(edges) + " 共" + edges.length);
sortEdges(edges);
for (int i = 0; i < edgeNum; i++) {
int p1 = getPosition(edges[i].start);
int p2 = getPosition(edges[i].end);
int m = getEnd(parent, p1);
int n = getEnd(parent, p2);
if (m != n) {
parent[m] = n;
rets[index++] = edges[i];
}
if (index == vertexs.length - 1) break;
}
System.out.println("最小生成树为=================");
for (int i = 0; i < index; i++) {
System.out.println(rets[i]);
}
}
}
class KData {
char start;
char end;
int weight;
public KData(char start, char end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
@Override
public String toString() {
return "KData [<" + start + ", " + end + ">= " + weight + "]";
}
}
@Test
public void test02() {
char[] vertexs = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int matrix[][] = {
/*B*
{0, 12, INF, INF, INF, 16, 14},
{12, 0, 10, INF, INF, 7, INF},
{INF, 10, 0, 3, 5, 6, INF},
{INF, INF, 3, 0, 4, INF, INF},
{INF, INF, 5, 4, 0, 2, 8},
{16, 7, 6, INF, 2, 0, 9},
{14, INF, INF, INF, 8, 9, 0}
};
KruskalAlgorithm kruskalAlgorithm = new KruskalAlgorithm(vertexs, matrix);
System.out.println("邻接矩阵============== \n");
kruskalAlgorithm.print();
System.out.println();
System.out.println("图中的边及权值-------------------------");
KData[] edges = kruskalAlgorithm.getEdges();
System.out.println("排序前=" + Arrays.toString(edges));
kruskalAlgorithm.sortEdges(edges);
System.out.println("排序后=" + Arrays.toString(edges));
System.out.println();
kruskalAlgorithm.kruskal();
}
}
T04最短路径
public class T04最短路径 {
private static final int INF = Integer.MAX_VALUE;
private class MatrixUDG {
private int mEdgNum;
private char[] mVexs;
private int[][] mMatrix;
public MatrixUDG() {
System.out.printf("input vertex number: ");
int vlen = readInt();
System.out.printf("input edge number: ");
int elen = readInt();
if (vlen < 1 || elen < 1 || (elen > (vlen * (vlen - 1)))) {
System.out.printf("input error: invalid parameters!\n");
return;
}
mVexs = new char[vlen];
for (int i = 0; i < mVexs.length; i++) {
System.out.printf("vertex(%d): ", i);
mVexs[i] = readChar();
}
mEdgNum = elen;
mMatrix = new int[vlen][vlen];
for (int i = 0; i < vlen; i++) {
for (int j = 0; j < vlen; j++) {
if (i == j)
mMatrix[i][j] = 0;
else
mMatrix[i][j] = INF;
}
}
for (int i = 0; i < elen; i++) {
System.out.printf("edge(%d):", i);
char c1 = readChar();
char c2 = readChar();
int weight = readInt();
int p1 = getPosition(c1);
int p2 = getPosition(c2);
if (p1 == -1 || p2 == -1) {
System.out.printf("input error: invalid edge!\n");
return;
}
mMatrix[p1][p2] = weight;
mMatrix[p2][p1] = weight;
}
}
public MatrixUDG(char[] vexs, int[][] matrix) {
int vlen = vexs.length;
mVexs = new char[vlen];
for (int i = 0; i < mVexs.length; i++)
mVexs[i] = vexs[i];
mMatrix = new int[vlen][vlen];
for (int i = 0; i < vlen; i++)
for (int j = 0; j < vlen; j++)
mMatrix[i][j] = matrix[i][j];
mEdgNum = 0;
for (int i = 0; i < vlen; i++)
for (int j = i + 1; j < vlen; j++)
if (mMatrix[i][j] != INF)
mEdgNum++;
}
private int getPosition(char ch) {
for (int i = 0; i < mVexs.length; i++)
if (mVexs[i] == ch)
return i;
return -1;
}
private char readChar() {
char ch = '0';
do {
try {
ch = (char) System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
} while (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')));
return ch;
}
private int readInt() {
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
public void print() {
System.out.printf("Martix Graph:\n");
for (int i = 0; i < mVexs.length; i++) {
for (int j = 0; j < mVexs.length; j++)
System.out.printf("%10d ", mMatrix[i][j]);
System.out.printf("\n");
}
}
private EData[] getEdges() {
int index = 0;
EData[] edges;
edges = new EData[mEdgNum];
for (int i = 0; i < mVexs.length; i++) {
for (int j = i + 1; j < mVexs.length; j++) {
if (mMatrix[i][j] != INF) {
edges[index++] = new EData(mVexs[i], mVexs[j], mMatrix[i][j]);
}
}
}
return edges;
}
private void sortEdges(EData[] edges, int elen) {
for (int i = 0; i < elen; i++) {
for (int j = i + 1; j < elen; j++) {
if (edges[i].weight > edges[j].weight) {
EData tmp = edges[i];
edges[i] = edges[j];
edges[j] = tmp;
}
}
}
}
private int getEnd(int[] vends, int i) {
while (vends[i] != 0)
i = vends[i];
return i;
}
public void dijkstra(int vs, int[] prev, int[] dist) {
boolean[] flag = new boolean[mVexs.length];
for (int i = 0; i < mVexs.length; i++) {
flag[i] = false;
prev[i] = 0;
dist[i] = mMatrix[vs][i];
}
flag[vs] = true;
dist[vs] = 0;
int k = 0;
for (int i = 1; i < mVexs.length; i++) {
int min = INF;
for (int j = 0; j < mVexs.length; j++) {
if (flag[j] == false && dist[j] < min) {
min = dist[j];
k = j;
}
}
flag[k] = true;
for (int j = 0; j < mVexs.length; j++) {
int tmp = (mMatrix[k][j] == INF ? INF : (min + mMatrix[k][j]));
if (flag[j] == false && (tmp < dist[j])) {
dist[j] = tmp;
prev[j] = k;
}
}
}
System.out.printf("dijkstra(%c): \n", mVexs[vs]);
for (int i = 0; i < mVexs.length; i++)
System.out.printf(" shortest(%c, %c)=%d\n", mVexs[vs], mVexs[i], dist[i]);
}
public void floyd(int[][] path, int[][] dist) {
for (int i = 0; i < mVexs.length; i++) {
for (int j = 0; j < mVexs.length; j++) {
dist[i][j] = mMatrix[i][j];
path[i][j] = j;
}
}
for (int k = 0; k < mVexs.length; k++) {
for (int i = 0; i < mVexs.length; i++) {
for (int j = 0; j < mVexs.length; j++) {
int tmp = (dist[i][k]==INF || dist[k][j]==INF) ? INF : (dist[i][k] + dist[k][j]);
if (dist[i][j] > tmp) {
dist[i][j] = tmp;
path[i][j] = path[i][k];
}
}
}
}
System.out.printf("floyd: \n");
for (int i = 0; i < mVexs.length; i++) {
for (int j = 0; j < mVexs.length; j++)
System.out.printf("%2d ", dist[i][j]);
System.out.printf("\n");
}
System.out.println("path>>>>>>>>");
for (int i = 0; i < mVexs.length; i++) {
for (int j = 0; j < mVexs.length; j++)
System.out.printf("%2d ", path[i][j]);
System.out.printf("\n");
}
}
private class EData {
char start;
char end;
int weight;
public EData(char start, char end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
}
;
}
@Test
public void test01() {
char[] vexs = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int matrix[][] = {
/*B*
{0, 12, INF, INF, INF, 16, 14},
{12, 0, 10, INF, INF, 7, INF},
{INF, 10, 0, 3, 5, 6, INF},
{INF, INF, 3, 0, 4, INF, INF},
{INF, INF, 5, 4, 0, 2, 8},
{16, 7, 6, INF, 2, 0, 9},
{14, INF, INF, INF, 8, 9, 0}};
MatrixUDG pG;
pG = new MatrixUDG(vexs, matrix);
int[] prev = new int[pG.mVexs.length];
int[] dist = new int[pG.mVexs.length];
int[][] path = new int[pG.mVexs.length][pG.mVexs.length];
int[][] floy = new int[pG.mVexs.length][pG.mVexs.length];
pG.floyd(path, floy);
}
}
5.查找
import org.junit.Test;
import java.util.Arrays;
public class T01 {
@Test
public void test01() {
int[] ints = {10, 10, 10, 10, 9, 10, 10};
for (int i = 0; i < ints.length; i++) {
if (ints[i] == 9) {
System.out.println("找到了");
return;
}
}
System.out.println("没找到……");
}
private int binary_search(int arr[], int target) {
int low = 0;
int high = arr.length - 1;
int middle = 0;
while (low < high) {
middle = (low + high) / 2;
if (arr[middle] == target) return middle;
if (arr[middle] > target) high = middle - 1;
else low = middle + 1;
}
return -1;
}
@Test
public void test02() {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int res = binary_search(arr, 5);
System.out.println(res);
}
private class T {
private class Index implements Comparable {
int key;
int start;
@Override
public int compareTo(Object o) {
Index o1 = (Index) o;
return this.key - o1.key;
}
}
Index[] indexs;
int arr[];
int space;
private void creat(int[] a, int num) {
this.arr = a;
this.indexs = new Index[num];
for (int i = 0; i < indexs.length; i++) {
indexs[i] = new Index();
}
this.space = a.length / indexs.length;
int j = 0;
for (int i = 0; i < indexs.length; i++) {
indexs[i].start = j;
j += space;
int max = 0;
for (int k = indexs[i].start; k < j; k++) {
if (a[k] > max) max = a[k];
}
indexs[i].key = max;
}
Arrays.sort(indexs);
}
private void search(int target) {
int i = 0;
while (i < indexs.length && indexs[i].key < target) {
i++;
}
if (i >= indexs.length) {
System.out.println("不存在");
return;
}
int start = indexs[i].start;
while (start < start + space && arr[start] != target) start++;
if (start >= start + space) {
System.out.println("不存在");
return;
} else {
System.out.println("已找到值下标:" + start);
}
}
}
@Test
public void test03() {
int a[] = {33, 42, 44, 38, 24, 48,
22, 12, 13, 8, 9, 20,
60, 58, 74, 49, 86, 53};
T t = new T();
t.creat(a, 3);
t.search(12);
}
private class node {
public int value;
public node left;
public node right;
public node() {
}
public node(int value) {
this.value = value;
this.left = null;
this.right = null;
}
public node(int value, node l, node r) {
this.value = value;
this.left = l;
this.right = r;
}
}
private class BinarySortTree {
node root;
public BinarySortTree() {
root = null;
}
public void makeEmpty()
{
root = null;
}
public boolean isEmpty()
{
return root == null;
}
public node findmin(node t)
{
if (t == null) {
return null;
} else if (t.left == null) {
return t;
} else return (findmin(t.left));
}
public node findmax(node t)
{
if (t == null) {
return null;
} else if (t.right == null) {
return t;
} else return (findmax(t.right));
}
public boolean isContains(int x)
{
node current = root;
if (root == null) {
return false;
}
while (current.value != x && current != null) {
if (x < current.value) {
current = current.left;
}
if (x > current.value) {
current = current.right;
}
if (current == null) {
return false;
}
}
if (current.value == x) {
return true;
}
return false;
}
public node insert(int x)
{
node current = root;
if (root == null) {
root = new node(x);
return root;
}
while (current != null) {
if (x < current.value) {
if (current.left == null) {
return current.left = new node(x);
} else {
current = current.left;
}
} else if (x > current.value) {
if (current.right == null) {
return current.right = new node(x);
} else {
current = current.right;
}
}
}
return current;
}
public node remove(int x, node t)
{
if (t == null) {
return null;
}
if (x < t.value) {
t.left = remove(x, t.left);
} else if (x > t.value) {
t.right = remove(x, t.right);
} else if (t.left != null && t.right != null)
{
t.value = findmin(t.right).value;
t.right = remove(t.value, t.right);
} else
{
if (t.left == null && t.right == null) {
t = null;
} else if (t.right != null) {
t = t.right;
} else if (t.left != null) {
t = t.left;
}
return t;
}
return t;
}
}
}
1.二叉排序树
private class Node2 {
int value;
private Node2 left;
private Node2 right;
public Node2(int value) {
this.value = value;
}
public Node2(int value, Node2 left, Node2 right) {
this.value = value;
this.left = left;
this.right = right;
}
public Node2() {
}
}
private class BinarySortTree {
Node2 root;
private void insert(int x) {
Node2 cur = root;
if (root == null) {
root = new Node2(x);
return;
}
while (cur != null) {
if (cur.value > x) {
if (cur.left == null) {
cur.left = new Node2(x);
return;
} else {
cur = cur.left;
}
} else {
if (cur.right == null) {
cur.right = new Node2(x);
return;
} else {
cur = cur.right;
}
}
}
}
private void search(int tar) {
if (root == null) {
System.out.println("无");
return;
}
Node2 cur = root;
while (cur != null) {
if (cur.value == tar) {
System.out.println("找到了");
return;
}
if (cur.value < tar) {
cur = cur.right;
} else {
cur = cur.left;
}
}
System.out.println("无");
}
private Node2 findMax(Node2 node) {
if (node == null) return null;
else if (node.right == null) {
return node;
} else {
return findMax(node.right);
}
}
private Node2 findMax() {
return findMax(root);
}
private Node2 findMin(Node2 node) {
if (node == null) return null;
else if (node.left == null) {
return node;
} else {
return findMin(node.left);
}
}
private Node2 findMin() {
return findMin(root);
}
private void remove(int tar) {
if (root == null) {
System.out.println("为空");
return;
}
Node2 cur = root;
while (cur != null) {
if (cur.value == tar) {
System.out.println("找到了");
if (cur.left != null && cur.right != null) {
Node2 min = findMin(cur.right);
cur.value = min.value;
min.value = tar;
cur.right = remove2(tar,cur.right);
} else {
if (cur.left == null && cur.right == null) {
cur = null;
} else if (cur.right != null) {
cur = cur.right;
} else {
cur = cur.left;
}
return;
}
}
if (cur.value < tar) {
cur = cur.right;
} else {
cur = cur.left;
}
}
}
private Node2 remove2(int tar, Node2 cur) {
if (cur == null) {
System.out.println("为空");
return null;
}
if (cur.value < tar) {
cur.right = remove2(tar,cur.right);
} else if (cur.value>tar){
cur.left = remove2(tar,cur.left);
}else if (cur.value == tar) {
System.out.println("找到了");
if (cur.left != null && cur.right != null) {
Node2 max = findMax(cur.right);
cur.value = max.value;
cur.right = remove2(tar,cur.right);
} else {
if (cur.left == null && cur.right == null) {
cur = null;
} else if (cur.right != null) {
cur = cur.right;
} else {
cur = cur.left;
}
return cur;
}
}
this.root = cur;
return cur;
}
private void remove2(int tar){
remove2(tar,root);
}
private void leverPrint() {
if (root == null) {
System.out.println("为空");
return;
}
Queue<Node2> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node2 poll = queue.poll();
if (poll.left != null) queue.add(poll.left);
if (poll.right != null) queue.add(poll.right);
System.out.print(poll.value + " ");
}
}
private void prePrint(Node2 node) {
if (node != null) {
System.out.print(node.value + " ");
prePrint(node.left);
prePrint(node.right);
}
}
private void prePrint() {
if (root == null) {
System.out.println("空");
return;
}
prePrint(root);
}
private void centerPrint(Node2 node) {
if (node != null) {
centerPrint(node.left);
System.out.print(node.value + " ");
centerPrint(node.right);
}
}
private void centerPrint() {
if (root == null) {
System.out.println("空");
return;
}
centerPrint(root);
}
private void postPrint(Node2 node) {
if (node != null) {
postPrint(node.left);
postPrint(node.right);
System.out.print(node.value + " ");
}
}
private void postPrint() {
if (root == null) {
System.out.println("空");
return;
}
postPrint(root);
}
private int getSize(Node2 root){
if (root == null){
return 0;
}
return getSize(root.left)+getSize(root.right)+1;
}
private int getSize(){
return getSize(root);
}
private int getHeight(Node2 node){
if (node == null){
return 0;
}else {
int left = getHeight(node.left);
int right = getHeight(node.right);
return (left>right)?(left+1):(right+1);
}
}
private int getHeight(){
return getHeight(root);
}
}
@Test
public void test04() {
BinarySortTree binarySortTree = new BinarySortTree();
binarySortTree.insert(1);
binarySortTree.insert(2);
binarySortTree.insert(3);
binarySortTree.insert(6);
binarySortTree.insert(5);
binarySortTree.insert(4);
System.out.println(binarySortTree.getHeight());
}
2.平衡二叉树
private class AvlTree2 {
private AvlNode root;
private AvlNode insert(AvlNode node, int data) {
if (node == null) {
node = new AvlNode(data);
node.height = 1;
return node;
}
if (node.data < data) {
node.rightChild = insert(node.rightChild,data);
node.height = Math.max(getHeight(node.rightChild),getHeight(node.leftChild))+1;
if (getHeight(node.rightChild) - getHeight(node.leftChild) == 2){
if (node.rightChild.data<data){
node = rotateLeft(node);
}else {
node = rotateRightLeft(node);
}
}
} else {
node.leftChild = insert(node.leftChild,data);
node.height = Math.max(getHeight(node.rightChild),getHeight(node.leftChild))+1;
if (getHeight(node.rightChild) - getHeight(node.leftChild) == -2){
if (node.leftChild.data<data){
node = rotateLeftRight(node);
}else {
node = rotateRight(node);
}
}
}
return node;
}
private void insert(int data){
root = insert(root,data);
}
private AvlNode rotateRight(AvlNode parent) {
AvlNode center = parent.leftChild;
parent.leftChild = center.rightChild;
center.rightChild = parent;
parent.height = Math.max(getHeight(parent.leftChild),getHeight(parent.rightChild))+1;
center.height = Math.max(getHeight(center.leftChild),getHeight(center.rightChild))+1;
return center;
}
private AvlNode rotateRightLeft(AvlNode parent) {
parent.rightChild = rotateRight(parent.rightChild);
parent = rotateLeft(parent);
return parent;
}
private AvlNode rotateLeft(AvlNode parent) {
AvlNode center = parent.rightChild;
parent.rightChild = center.leftChild;
center.leftChild = parent;
parent.height = Math.max(getHeight(parent.leftChild),getHeight(parent.rightChild))+1;
center.height = Math.max(getHeight(center.leftChild),getHeight(center.rightChild))+1;
return center;
}
private AvlNode rotateLeftRight(AvlNode parent) {
parent.leftChild = rotateLeft(parent.leftChild);
parent = rotateRight(parent);
return parent;
}
private int getHeight(AvlNode node) {
if (node == null){
return 0;
}else {
return node.height;
}
}
private AvlNode deleteMin(AvlNode node){
if (node == null) return node;
if (node.leftChild == null) return node.rightChild;
node.leftChild = deleteMin(node.leftChild);
if (getHeight(node.rightChild) - getHeight(node.leftChild) == 2){
node = rotateLeft(node);
}
return node;
}
public void deleteMin() {
root = deleteMin(root);
}
private AvlNode deleteMax(AvlNode node){
if (node == null) return node;
if (node.rightChild == null)
return node.leftChild;
node.rightChild = deleteMax(node.rightChild);
if (getHeight(node.leftChild) - getHeight(node.rightChild) == 2){
node = rotateRight(node);
}
return node;
}
public void deleteMax() {
root = deleteMax(root);
}
private AvlNode delete(AvlNode node,int data){
if (node == null) return node;
if (node.data<data){
node.rightChild = delete(node.rightChild,data);
if (getHeight(node.leftChild)- getHeight(node.rightChild) ==2){
node = rotateLeft(node.rightChild);
}
}else if (node.data>data){
node.leftChild = delete(node.leftChild,data);
if (getHeight(node.rightChild)-getHeight(node.leftChild) ==2){
node = rotateRight(node.rightChild);
}
}else if (node.data == data){
if (node.leftChild == null) return node.rightChild;
if (node.rightChild == null) return node.leftChild;
AvlNode min = getMin(node.rightChild);
min.rightChild = deleteMin(node.rightChild);
min.leftChild = node.leftChild;
node = min;
if (getHeight(node.leftChild) - getHeight(node.rightChild) == 2){
node = rotateRight(node);
}
}
return node;
}
private void delete(int data){
root = delete(root,data);
}
private AvlNode getMin(AvlNode node) {
if (node == null)return node;
while (node.leftChild!=null)node = node.leftChild;
return node;
}
private void leverPrint(AvlNode node){
if (node == null){
System.out.println("无");
return;
}
Queue<AvlNode> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()){
AvlNode poll = queue.poll();
System.out.print(poll.data+" ");
if (poll.leftChild!=null) queue.add(poll.leftChild);
if (poll.rightChild!=null)queue.add(poll.rightChild);
}
System.out.println("高度:"+getHeight(node));
}
private void leverPrint(){
leverPrint(root);
}
}
@Test
public void test05() {
AvlTree2 avlTree = new AvlTree2();
Scanner scanner = new Scanner(System.in);
int i1 = scanner.nextInt();
for (int i = 0; i < i1; i++) {
avlTree.insert(scanner.nextInt());
}
avlTree.leverPrint();
avlTree.delete(5);
avlTree.leverPrint();
}
6. 排序
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class T01 {
@Test
public void test01() {
int[] arr = {1, 2, 3, 6, 5, 4};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
@Test
public void test02() {
int[] arr = {1, 2, 3, 6, 5, 4};
for (int i = 0; i < arr.length - 1; i++) {
boolean flag = true;
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
flag = false;
}
}
if (flag) {
break;
}
}
System.out.println(Arrays.toString(arr));
}
int[] arr = {1, 2, 3, 6, 5, 4};
private int[] swap(int pre, int next) {
int swap = arr[pre];
arr[pre] = arr[next];
arr[next] = swap;
return arr;
}
private int[] swap2(int pre, int next) {
int swap = arr[next];
arr[next] = arr[pre];
arr[pre] = swap;
return arr;
}
@Test
public void test03() {
for (int i = 0; i < arr.length - 1; i++) {
int temp = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[temp] > arr[j]) {
temp = j;
}
}
arr = swap(i, temp);
}
System.out.println(Arrays.toString(arr));
}
@Test
public void test04() {
int j = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
int temp = arr[i];
for (j = i - 1; j >= 0 && arr[j] > temp; j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = temp;
}
}
System.out.println(Arrays.toString(arr));
}
public static void shellSortSmallToBig(int[] data) {
int j = 0;
int temp = 0;
for (int increment = data.length / 2; increment > 0; increment /= 2) {
System.out.println("increment:" + increment);
for (int i = increment; i < data.length; i++) {
temp = data[i];
for (j = i - increment; j >= 0; j -= increment) {
if (temp < data[j]) {
data[j + increment] = data[j];
} else {
break;
}
}
data[j + increment] = temp;
}
for (int i = 0; i < data.length; i++)
System.out.print(data[i] + " ");
System.out.println();
}
}
@Test
public void test05() {
int[] data = new int[]{26, 53, 67, 48, 57, 13, 48, 32, 60, 50};
shellSortSmallToBig(data);
System.out.println(Arrays.toString(data));
}
private void heapSort(int[] arr) {
for (int i = (arr.length - 1) / 2; i >= 0; i--) {
adjustHeap(arr, i, arr.length);
}
for (int i = arr.length - 1; i > 0; i--) {
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
adjustHeap(arr, 0, i);
}
}
private void adjustHeap(int[] arr, int parent, int length) {
int temp = arr[parent];
int lChild = 2 * parent + 1;
while (lChild < length) {
int rChild = lChild + 1;
if (rChild < length && arr[lChild] < arr[rChild]) {
lChild++;
}
if (temp >= arr[lChild]) {
break;
}
arr[parent] = arr[lChild];
parent = lChild;
lChild = 2 * lChild + 1;
}
arr[parent] = temp;
}
@Test
public void test06() {
int[] arr = {16, 7, 3, 20, 17, 8};
heapSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= high) {
if (a[i] < a[j]) {
temp[k++] = a[i++];
} else {
temp[k++] = a[j++];
}
}
while (i <= mid) {
temp[k++] = a[i++];
}
while (j <= high) {
temp[k++] = a[j++];
}
for (int k2 = 0; k2 < temp.length; k2++) {
a[k2 + low] = temp[k2];
}
}
public void mergeSort(int[] a, int low, int high) {
int mid = (low + high) / 2;
if (low < high) {
mergeSort(a, low, mid);
mergeSort(a, mid + 1, high);
merge(a, low, mid, high);
System.out.println(Arrays.toString(a));
}
}
@Test
public void test07() {
int a[] = {51, 46, 20, 18, 65, 97, 82, 30, 77, 50};
mergeSort(a, 0, a.length - 1);
System.out.println("排序结果:" + Arrays.toString(a));
}
public void quickSort(int[] a, int l, int r) {
if (l < r) {
int i,j,x;
i = l;
j = r;
x = a[i];
while (i < j) {
while(i < j && a[j] > x)
j--;
if(i < j)
a[i++] = a[j];
while(i < j && a[i] < x)
i++;
if(i < j)
a[j--] = a[i];
}
a[i] = x;
quickSort(a, l, i-1);
quickSort(a, i+1, r);
}
}
@Test
public void test08() {
int i;
int a[] = {30,40,60,10,20,50};
System.out.printf("before sort:");
for (i=0; i<a.length; i++)
System.out.printf("%d ", a[i]);
System.out.printf("\n");
quickSort(a, 0, a.length-1);
System.out.printf("after sort:");
for (i=0; i<a.length; i++)
System.out.printf("%d ", a[i]);
System.out.printf("\n");
}
}