java数据结构期末复习_java数据结构复习02
1.遞歸問題
1.1計算階乘
packageinterview.recursion;importjava.util.Scanner;public classFact {public static voidmain(String[] args) {
System.out.println("請輸入n的值:");
Scanner in= newScanner(System.in);int n =in.nextInt();int num =fact(n);
System.out.println(n+ "的階乘為:" +num);
}public static int fact(intn) {if (n == 1) {return 1;
}return n * fact(n - 1);
}
}
1.2計算斐波那契數列
Fibonacci sequence:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ……
packageinterview.recursion;importjava.util.Scanner;public classFib {public static int fib(intn) {if (n == 0) {return 0;
}else if (n == 1) {return 1;
}else{return fib(n - 1) + fib(n - 2);
}
}public static voidmain(String[] args) {
System.out.println("請輸入n的值:");
Scanner in= newScanner(System.in);int n =in.nextInt();int num =fib(n);
System.out.println("第" + n + "個值的fib為:" + +num);
}
}
1.3計算最大公約數(輾轉相除法)
packageinterview.recursion;importjava.util.Scanner;public classGcd {public static int gcd(int max, intmin) {if (min == 0) {returnmax;
}else{return gcd(min, max %min);
}
}public static voidmain(String[] args) {
System.out.println("請輸入max的值:");
Scanner in= newScanner(System.in);int max =in.nextInt();
System.out.println("請輸入min的值:");int min =in.nextInt();int num =gcd(max, min);
System.out.println(max+ "和" + min + "的最大公約數為:" +num);
}
}
1.4漢諾塔問題(遞歸)
問題描述
三個柱子,起初有若干個按大小關系順序安放的盤子,需要全部移動到另外一個柱子上。移動規則:在小圓盤上不能放大圓盤,在三根柱子之間一次只能移動一個圓盤。
移動次數: f(n)=2n -1
解法思路
使用遞歸算法進行處理。
漢諾塔的算法大概有3個步驟:
(1)把a上的n-1個盤通過c移動到b。
(2)把a上的最下面的盤移到c。
(3)因為n-1個盤全在b上了,所以把b當做a重復以上步驟就好了。
在網上找到一個3階的漢諾塔遞歸過程示意圖,參考一下。
packagecn.jxufe.ch06_hanoitowers;public classHanoiTowers {/*** 漢諾塔問題:所有的盤子,剛開始都在塔座A上,要求將所有的盤子從塔座A移動到塔座C,每次只能移動一個盤子,且
* 任何盤子不能放在比自己小的盤子上。
*
*@paramtopN:移動的盤子數
*@paramfrom:從哪個塔座開始
*@paraminter:中間塔座
*@paramto;目標塔座*/
public static void doTower(int topN, char from, char inter, charto) {if (topN == 1) {
System.out.println("盤子1,從" + from + "塔座到" + to + "塔座");return;
}else{
doTower(topN- 1, from, to, inter);
System.out.println("盤子" + topN + ",從" + from + "塔座到" + to + "塔座");
doTower(topN- 1, inter, from, to);
}
}
}
packagecn.jxufe.ch06_hanoitowers;public classTestHanoiTowers {public static voidmain(String[] args) {
HanoiTowers.doTower(4,'A','B','C');
}
}
1.5瓶蓋問題
packagetest;/** 描述:每 3 個可樂蓋可兌換 1 瓶子可樂,求買 n 瓶可樂最終可獲得的可樂瓶子數。*/
importjava.util.Scanner;public classT03 {public static int times = 1;public static voidmain(String[] args) {
Scanner input= newScanner(System.in);
System.out.print("輸入購買的可樂數:");
times= 1;int j =input.nextInt();int i =func(j);
System.out.println("--------------------------");
System.out.println("總共可獲得 " + i + " 瓶\n\n");
}public static int func(inti) {if (i < 3) {
System.out.println("最終剩下 " + i + " 個瓶蓋,不足以兌換");returni;
}else{
System.out.println("第 " + times++ + " 次兌換," + "本次兌換總共有 " + i + " 個瓶蓋,用 " + (i - i % 3) + " 個瓶蓋換了 " + i / 3
+ " 瓶可樂,剩余 " + i % 3 + " 個瓶蓋可用于下次兌換");return ((i - i % 3) + func(i / 3 + i % 3));
}
}
}
1.6走樓梯
題目描述:
一個臺階總共有n級,如果一次可以跳1級,也可以跳2級。求總共有多少總跳法。
思路:當n大于2的時候,每次可以選擇走2級也可以選擇走1級,所有都有兩種方案。即f(n-1)+f(n-2)
packageinterview.recursion;importjava.util.Scanner;public classStairs {public static int solve(intn) {if (n == 1) {return 1;
}else if (n == 2) {return 2;
}else{return solve(n - 1) + solve(n - 2);
}
}public static voidmain(String[] args) {
System.out.println("請輸入n的值:");
Scanner in= newScanner(System.in);int n =in.nextInt();int num =solve(n);
System.out.println("總共有" + num + "種走法");
}
}
2.二叉樹
2.1插入和查找
packagecn.jxufe.ch07_tree;/*** 二叉樹節點*/
public classNode {//數據項
public intdata;publicString sdata;publicNode leftChild;publicNode rightChild;public Node(intdata,String sdata) {this.data =data;this.sdata =sdata;
}
}
packagecn.jxufe.ch07_tree;/*** 二叉樹*/
public classTree {//根節點
publicNode root;/*** 插入節點*/
public void insert(intvalue,String sdata) {//封裝節點
Node newNode = newNode(value,sdata);//引用當前節點
Node current =root;//引用父節點
Node parent;//如果root為null,也就是第一次插入的節點
if (root == null) {
root=newNode;return;
}else{while (true) {//父節點指向當前節點
parent =current;//如果當前節點指向的數據,比插入的要大,則向左走
if (value
current=current.leftChild;if (current == null) {
parent.leftChild=newNode;return;
}
}else{
current=current.rightChild;if (current == null) {
parent.rightChild=newNode;return;
}
}
}
}
}/*** 查找節點*/
public Node find(intvalue) {//引用當前節點,從根節點開始
Node current =root;//只要查找的值,不等于當前節點的值
while (current.data !=value) {//比較查找值,與當前節點值的大小
if (current.data >value) {
current=current.leftChild;
}else{
current=current.rightChild;
}//如果查找不到
if (current == null) {return null;
}
}returncurrent;
}/*** 刪除節點*/
public void delete(intvalue) {
}
}
packagecn.jxufe.ch07_tree;public classTestTree {public static voidmain(String[] args) {
Tree tree= newTree();
tree.insert(10, "zhangsan");
tree.insert(20, "lisi");
tree.insert(3, "wangwu");
tree.insert(14, "zhaoliu");
tree.insert(76, "zhouqi");
System.out.println(tree.root.data);
System.out.println(tree.root.leftChild.data);
System.out.println(tree.root.rightChild.data);
System.out.println(tree.root.rightChild.leftChild.data);
System.out.println(tree.root.rightChild.rightChild.data);
Node node= tree.find(20);
System.out.println(node.data+ "," +node.sdata);
System.out.println(node.rightChild.data+ "," +node.rightChild.sdata);
}
}
2.2遍歷二叉樹
packagecn.jxufe.ch07_tree;/*** 二叉樹節點*/
public classNode {//數據項
public intdata;publicString sdata;publicNode leftChild;publicNode rightChild;public Node(intdata,String sdata) {this.data =data;this.sdata =sdata;
}
}
packagecn.jxufe.ch07_tree;/*** 二叉樹*/
public classTree {//根節點
publicNode root;/*** 插入節點*/
public void insert(intvalue, String sdata) {//封裝節點
Node newNode = newNode(value, sdata);//引用當前節點
Node current =root;//引用父節點
Node parent;//如果root為null,也就是第一次插入的節點
if (root == null) {
root=newNode;return;
}else{while (true) {//父節點指向當前節點
parent =current;//如果當前節點指向的數據,比插入的要大,則向左走
if (value
current=current.leftChild;if (current == null) {
parent.leftChild=newNode;return;
}
}else{
current=current.rightChild;if (current == null) {
parent.rightChild=newNode;return;
}
}
}
}
}/*** 查找節點*/
public Node find(intvalue) {//引用當前節點,從根節點開始
Node current =root;//只要查找的值,不等于當前節點的值
while (current.data !=value) {//比較查找值,與當前節點值的大小
if (current.data >value) {
current=current.leftChild;
}else{
current=current.rightChild;
}//如果查找不到
if (current == null) {return null;
}
}returncurrent;
}/*** 刪除節點*/
public void delete(intvalue) {
}/*** 前序遍歷*/
public voidfrontOrder(Node localNode) {if (localNode != null) {//訪問根節點
System.out.print(localNode.data + ":" + localNode.sdata + " ");//前序遍歷左子樹
frontOrder(localNode.leftChild);//前序遍歷右子樹
frontOrder(localNode.rightChild);
}
}/*** 中序遍歷*/
public voidinOrder(Node localNode) {if (localNode != null) {//中序遍歷左子樹
inOrder(localNode.leftChild);//訪問根節點
System.out.print(localNode.data + "," + localNode.sdata + " ");//中序遍歷右子樹
inOrder(localNode.rightChild);
}
}/*** 后序遍歷*/
public voidafterOrder(Node localNode) {if (localNode != null) {//后序遍歷左子樹
afterOrder(localNode.leftChild);//后序遍歷右子樹
afterOrder(localNode.rightChild);//訪問根節點
System.out.print(localNode.data + "," + localNode.sdata + " ");
}
}
}
packagecn.jxufe.ch07_tree;public classTestTree {public static voidmain(String[] args) {
Tree tree= newTree();
tree.insert(10, "zhangsan");
tree.insert(20, "lisi");
tree.insert(3, "wangwu");
tree.insert(14, "zhaoliu");
tree.insert(76, "zhouqi");
tree.insert(13, "zhuba");
System.out.println("前序遍歷:");
tree.frontOrder(tree.root);
System.out.println();
System.out.println("中序遍歷:");
tree.inOrder(tree.root);
System.out.println();
System.out.println("后序遍歷:");
tree.afterOrder(tree.root);
}
}
2.3刪除二叉樹節點
packageinterview;public classTree {privateNode root;public void insertNode(intdata, String sdata) {
Node newNode= newNode(data, sdata);//引用當前節點
Node current =root;
Node parent;//如果root為null,也就是第一次插入
if (root == null) {
root=newNode;
}else{while (true) {
parent=current;//如果當前節點指向的數據,比插入的節點數據要大,則向左走
if (data
current=current.leftChildNode;if (current == null) {
parent.leftChildNode=newNode;return;
}
}else{
current=current.rightChildNode;if (current == null) {
parent.rightChildNode=newNode;return;
}
}
}
}
}public Node findNode(intvalue) {
Node current=root;while (current.data !=value) {if (current.data >value) {
current=current.leftChildNode;
}else{
current=current.rightChildNode;
}if (current == null) {return null;
}
}returncurrent;
}public voidfontOrder(Node root) {if (root != null) {
System.out.println(root.data);
fontOrder(root.leftChildNode);
fontOrder(root.rightChildNode);
}
}publicNode getSuccessor(Node delNode) {
Node successor=delNode;
Node successorParent=delNode;
Node current=delNode.rightChildNode;while (current != null) {
successorParent=successor;
successor=current;
current=current.leftChildNode;
}if(successor !=delNode.rightChildNode) {
successorParent.leftChildNode=successor.rightChildNode;
successor.rightChildNode=delNode.rightChildNode;
}returnsuccessor;
}public boolean deleteNode(intvalue) {//引用當前節點為根節點
Node current =root;//引用當前節點的父節點
Node parent =root;//是否為左子樹
boolean isLeftchild = true;//查找
while (current.data !=value) {
parent=current;//比較
if (current.data >value) {
current=current.leftChildNode;
isLeftchild= true;
}else{
current=current.rightChildNode;
isLeftchild= false;
}if (current == null) {return false;
}
}//刪除
if (current.leftChildNode == null && current.rightChildNode == null) {//1. 刪除的節點為葉子節點
if (current ==root) {
root= null;
}else if (isLeftchild) {//如果它是父節點的左子節點
parent.leftChildNode = null;
}else{
parent.rightChildNode= null;
}
}else if (current.rightChildNode == null) { //2. 該節點有一個子節點,且為左子節點
if (current ==root) {
root=current.leftChildNode;
}else if(isLeftchild) {
parent.leftChildNode=current.leftChildNode;
}else{
parent.rightChildNode=current.leftChildNode;
}
}else if (current.leftChildNode == null) { //該節點只有一個節點,且為右子節點
if (current ==root) {
root=current.rightChildNode;
}else if(isLeftchild) {
parent.leftChildNode=current.rightChildNode;
}else{
parent.rightChildNode=current.rightChildNode;
}
}else{
Node successor= getSuccessor(current);//查找中序后繼節點
if(current == root) { //以下是完成替換功能
root =successor;
}else if(isLeftchild) {
parent.leftChildNode=successor;
}else{
parent.rightChildNode=successor;
}
successor.leftChildNode=current.leftChildNode;
}return true;
}public static voidmain(String[] args) {
Tree tree= newTree();
tree.insertNode(10, "zhangsan");
tree.insertNode(20, "lisi");
tree.insertNode(3, "wangwu");
tree.insertNode(14, "zhaoliu");
tree.insertNode(76, "zhouqi");
tree.insertNode(5, "niaho");//System.out.println(tree.root.data);//System.out.println(tree.root.leftChildNode.data);//System.out.println(tree.root.rightChildNode.data);//System.out.println(tree.root.rightChildNode.leftChildNode.data);//System.out.println(tree.root.rightChildNode.rightChildNode.data);//Node node = tree.findNode(20);//System.out.println(node.data + "," + node.sdata);//System.out.println(node.rightChildNode.data + "," +//node.rightChildNode.sdata);
tree.fontOrder(tree.root);
tree.deleteNode(3);
System.out.println("--------------------");
tree.fontOrder(tree.root);
tree.deleteNode(20);
System.out.println("------------------------");
tree.fontOrder(tree.root);
}
}classNode {//數據域
public intdata;publicString sdata;//指針域
publicNode leftChildNode;publicNode rightChildNode;public Node(intdata, String sdata) {//TODO Auto-generated constructor stub
this.data =data;this.sdata =sdata;
}
}
2.4根據中序和后序,求前序遍歷
packageexam;importjava.util.Arrays;public classMain {public static voidmain(String[] args) {//TODO Auto-generated method stub//Scanner sc = new Scanner(System.in);//String in = sc.nextLine();
String in = "dgbaechf";char[] inArray =in.toCharArray();//String last = sc.nextLine();
String last = "gbdehfca";char[] lastArray =last.toCharArray();//System.out.println(Arrays.toString(preArray));//System.out.println(Arrays.toString(inArray));
Node node =buildTree(inArray, lastArray);
frontOrder(node);
}public static Node buildTree(char[] inorder, char[] postorder) {if (inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0) {return null;
}//將后序遍歷的最后一個節點取出為根
Node root = new Node(postorder[postorder.length - 1]);int i = 0;//記錄中序遍歷根的位置
for (; i < inorder.length; i++) {if (postorder[postorder.length - 1] ==inorder[i]) {break;
}
}//構造左子樹
char[] leftIn = Arrays.copyOfRange(inorder, 0, i);char[] leftPost = Arrays.copyOfRange(postorder, 0, i);//構造右子樹
char[] rightIn = Arrays.copyOfRange(inorder, i + 1, inorder.length);char[] rightPost = Arrays.copyOfRange(postorder, i, postorder.length - 1);//左子樹
root.leftChild =buildTree(leftIn, leftPost);//右子樹
root.rightChild =buildTree(rightIn, rightPost);returnroot;
}/*** 前序遍歷*/
public static voidfrontOrder(Node localNode) {if (localNode != null) {//訪問根節點
System.out.print(localNode.data + " ");//前序遍歷左子樹
frontOrder(localNode.leftChild);//前序遍歷右子樹
frontOrder(localNode.rightChild);
}
}
}/*** 二叉樹節點*/
classNode {//數據項
public chardata;publicNode leftChild;publicNode rightChild;public Node(chardata) {this.data =data;
}
}
2.5二叉樹高度
packagedatastruct.t04tree;/*** 二叉樹節點
**/
public classNode {public intdata;publicNode leftChild;publicNode rightChild;public Node(intdata) {this.data =data;
}public voidsetLeftChild(Node leftChild) {this.leftChild =leftChild;
}public voidsetRightChild(Node rightChild) {this.rightChild =rightChild;
}public static Node createNode(intdata) {
Node node= newNode(data);
node.leftChild= node.rightChild = null;returnnode;
}public static voidsetChild(Node node, Node leftChild, Node rightChild) {
node.setLeftChild(leftChild);
node.setRightChild(rightChild);
}
}
packagedatastruct.t04tree;public classBiTree {public static intgetTreeHeight(Node root) {if (root == null) {return 0;
}else{int leftHeight =getTreeHeight(root.leftChild);int rightHeight =getTreeHeight(root.rightChild);return Math.max(leftHeight, rightHeight) + 1;
}
}public static voidmain(String[] args) {//快速構建一棵二叉樹
Node root = Node.createNode(1);
Node node2= Node.createNode(2);
Node node3= Node.createNode(3);
Node node4= Node.createNode(4);
Node node5= Node.createNode(5);
Node node6= Node.createNode(6);
Node node7= Node.createNode(7);
Node node8= Node.createNode(8);
Node.setChild(root, node2, node3);
Node.setChild(node2, node4, node5);
Node.setChild(node3,null, node7);
Node.setChild(node4,null, node8);
Node.setChild(node5, node6,null);//樹的高度
int height =getTreeHeight(root);
System.out.print("樹的高度為:");
System.out.println(height);
}
}
2.6表達式樹的輸出與求值
表達式樹的特征:葉節點是運算數,非葉節點一定是運算符
輸入格式:
第一行給出節點的個數N,每個節點的編號為0 ~ N-1
接下來N行每行分別給出:
該節點的編號、該節點的操作數/操作符、該節點的左孩子編號、右孩子編號(-1表示NULL)
輸出格式:
第一行輸出該表達式樹的中綴表達式,該用括號的地方需要用括號括起來。
第二行輸出該表達式樹的前綴表達式。
第二行輸出該表達式樹的后綴表達式。
第四行輸出該表達式樹的計算結果,保留兩位小數。
樣例輸入:
11
0 - 1 2
1 + 3 4
2 / 5 6
3 4 -1 -1
4 * 7 8
5 6 -1 -1
6 3 -1 -1
7 1 -1 -1
8 - 9 10
9 5 -1 -1
10 2 -1 -1
樣例輸出:
(4+(1*(5-2)))-(6/3)- + 4 * 1 - 5 2 / 6 3
4 1 5 2 - * + 6 3 / -
5.00
packagedatastruct.t04tree.exptree;public classNode {chardata;
Node leftChild;
Node rightChild;
}
packagedatastruct.t04tree.exptree;importjava.util.Scanner;public classExpTree {//中綴表達式
public static void inOrder(Node root, intlayer) {if (root == null)return;if (root.leftChild == null && root.rightChild == null) {//葉結點是操作數,直接輸出,不加括號
System.out.print(root.data + " ");
}else{//非葉節點是操作符,需加括號(第0層根節點除外)
if (layer > 0) {
System.out.print("(");
}
inOrder(root.leftChild, layer+ 1);
System.out.print(root.data+ " ");
inOrder(root.rightChild, layer+ 1);if (layer > 0) {
System.out.print(")");
}
}
}//前綴表達式
public static voidpreOrder(Node root) {if (root == null)return;
System.out.print(root.data+ " ");
preOrder(root.leftChild);
preOrder(root.rightChild);
}//后綴表達式
public static voidpostOrder(Node root) {if (root == null)return;
postOrder(root.leftChild);
postOrder(root.rightChild);
System.out.print(root.data+ " ");
}public static doublegetExpTree(Node root) {if (root == null) {return 0;
}if (root.leftChild == null && root.rightChild == null) {//葉節點,節點存放的是 操作數
return root.data - '0'; //將字符轉換成數字
}//非葉結點,節點存放的是 操作符
double a =getExpTree(root.leftChild);double b =getExpTree(root.rightChild);returncal(a, b, root.data);
}public static double cal(double a, double b, charop) {switch(op) {case '+':return a +b;case '-':return a -b;case '*':return a *b;case '/':return a /b;default:return 0;
}
}public static voidmain(String[] args) {
Scanner input= newScanner(System.in);
System.out.println("請輸入節點的個數");int N =input.nextInt();
Node[] nodes= newNode[N];for (int i = 0; i < N; i++) {
nodes[i]= newNode();
}
System.out.println("請輸入index,data,l,r");for (int i = 0; i < N; i++) {int index =input.nextInt();char data = input.next().charAt(0);int l =input.nextInt();int r =input.nextInt();
nodes[index].data=data;
nodes[index].leftChild= (l != -1 ? nodes[l] : null);
nodes[index].rightChild= (r != -1 ? nodes[r] : null);
}
Node root= nodes[0];
inOrder(root,0);
System.out.println();
preOrder(root);
System.out.println();
postOrder(root);
System.out.println();double value =getExpTree(root);
System.out.println(value);
}
}
2.7求二叉樹指定節點所在層數(假設根節點的層數為1)
1.方法1
packagedatastruct.t04tree.layer;classNode {intdata;
Node leftChild;
Node rightChild;public Node(intdata) {this.data =data;
}public voidsetChild(Node leftChild, Node rightChild) {this.leftChild =leftChild;this.rightChild =rightChild;
}
}public classNodeLayer {static int layer = 0;static boolean flag = false;//flag標記可用于提前快速結束遞歸的執行
public static void getNodeLayer(Node root, intvalue) {if (root == null)return;if(flag)return;
layer++;if (root.data ==value) {
System.out.println(layer);
flag= true;return;
}
getNodeLayer(root.leftChild, value);
getNodeLayer(root.rightChild, value);
layer--;
}public static voidmain(String[] args) {
Node root= new Node(1);
Node node2= new Node(2);
Node node3= new Node(3);
Node node4= new Node(4);
Node node5= new Node(5);
Node node6= new Node(6);
Node node7= new Node(7);
Node node8= new Node(8);
root.setChild(node2, node3);
node2.setChild(node4, node5);
node3.setChild(null, node6);
node5.setChild(node7,null);
node7.setChild(null, node8);int value = 7;
getNodeLayer(root, value);
}
}
2.方法2
packagedatastruct.t04tree.layer;classNode {intdata;
Node leftChild;
Node rightChild;public Node(intdata) {this.data =data;
}public voidsetChild(Node leftChild, Node rightChild) {this.leftChild =leftChild;this.rightChild =rightChild;
}
}public classNodeLayer {
static boolean flag = false;public static void getNodeLayer(Node root, int value, intlayer) {if (root == null)return;if(flag)return;if (root.data ==value) {
System.out.println(layer);
flag= true;return;
}
getNodeLayer(root.leftChild, value, layer+ 1);
getNodeLayer(root.rightChild, value, layer+ 1);
}public static voidmain(String[] args) {
Node root= new Node(1);
Node node2= new Node(2);
Node node3= new Node(3);
Node node4= new Node(4);
Node node5= new Node(5);
Node node6= new Node(6);
Node node7= new Node(7);
Node node8= new Node(8);
root.setChild(node2, node3);
node2.setChild(node4, node5);
node3.setChild(null, node6);
node5.setChild(node7,null);
node7.setChild(null, node8);int value = 7;
getNodeLayer(root, value, 1);
}
}
2.8求某節點到根節點的路徑
對于如下二叉樹,節點 7 位于第 4 層,其到跟節點的路徑為 1 2 5 7
packagedatastruct.t04tree.path;importjava.util.Stack;classNode {intdata;
Node leftChild;
Node rightChild;public Node(intdata) {this.data =data;
}public voidsetChild(Node leftChild, Node rightChild) {this.leftChild =leftChild;this.rightChild =rightChild;
}
}public classTreePath {static Stack path = new Stack<>();static boolean flag = false;public static void getNodePath(Node root, intvalue) {if (root == null)return;if(flag)return;
path.add(root.data);if (root.data ==value) {for(Integer integer : path) {
System.out.print(integer+ " ");
}
flag= true;return;
}
getNodePath(root.leftChild, value);
getNodePath(root.rightChild, value);
path.pop();
}public static voidmain(String[] args) {
Node root= new Node(1);
Node node2= new Node(2);
Node node3= new Node(3);
Node node4= new Node(4);
Node node5= new Node(5);
Node node6= new Node(6);
Node node7= new Node(7);
Node node8= new Node(8);
root.setChild(node2, node3);
node2.setChild(node4, node5);
node3.setChild(null, node6);
node5.setChild(node7,null);
node7.setChild(null, node8);int value = 7;
getNodePath(root, value);
}
}
2.9全排列問題
輸出數字1~N所能組成的所有全排列
packagedatastruct.t04tree.permutation;importjava.util.Stack;public classPermutation {public static int MAXN = 10;static boolean[] isUsed = new boolean[MAXN];static Stack nums = new Stack<>();static intN;/***@paramindex
* 表示第幾層*/
public static void DFS(intindex) {if (index >=N) {for(Integer i : nums)
System.out.print(i+ " ");
System.out.println();return;
}for (int i = 1; i <= N; i++) {if(isUsed[i])continue;
nums.push(i);
isUsed[i]= true;
DFS(index+ 1);
nums.pop();
isUsed[i]= false;
}
}public static voidmain(String[] args) {
N= 3;
DFS(0);//從第0層開始搜索
}
}
3.紅黑樹
4.hash表
4.1直接將關鍵字作為索引
packagech15;public classInfo {private intkey;privateString name;public Info(intkey, String name) {//TODO Auto-generated constructor stub
this.key =key;this.name =name;
}public intgetKey() {returnkey;
}public void setKey(intkey) {this.key =key;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}
}
packagech15;public classHashTable {privateInfo[] arr;publicHashTable() {//TODO Auto-generated constructor stub
arr = new Info[100];
}public HashTable(intmaxSize) {
arr= newInfo[maxSize];
}public voidinsert(Info info) {
arr[info.getKey()]=info;
}public Info find(intkey) {returnarr[key];
}
}
packagech15;public classTestHashTable {public static voidmain(String[] args) {
HashTable hTable= newHashTable();
hTable.insert(new Info(10, "張三"));
hTable.insert(new Info(15, "李四"));
System.out.println(hTable.find(15).getName());
}
}
4.2將單詞轉化為索引
packagech15;public classInfo {privateString key;privateString name;publicInfo(String key, String name) {//TODO Auto-generated constructor stub
this.key =key;this.name =name;
}publicString getKey() {returnkey;
}public voidsetKey(String key) {this.key =key;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}
}
packagech15;public classHashTable {privateInfo[] arr;publicHashTable() {//TODO Auto-generated constructor stub
arr = new Info[100];
}public HashTable(intmaxSize) {
arr= newInfo[maxSize];
}public voidinsert(Info info) {
arr[hashCode(info.getKey())]=info;
}publicInfo find(String key) {returnarr[hashCode(key)];
}public inthashCode(String key) {int hashValue = 0;for (int i = key.length() - 1; i >= 0; i--) {int letter = key.charAt(i) - 96;
hashValue+=letter;
}returnhashValue;
}
}
packagech15;public classTestHashTable {public static voidmain(String[] args) {
HashTable hTable= newHashTable();
hTable.insert(new Info("zhangsan", "張三"));
hTable.insert(new Info("lisi", "李四"));
System.out.println(hTable.find("zhangsan").getName());
}
}
以上方法也會存在一定的問題,當hashcode相同的時候。
packagech15;public classTestHashTable {public static voidmain(String[] args) {
HashTable hTable= newHashTable();
hTable.insert(new Info("abc", "張三"));
hTable.insert(new Info("bca", "李四"));
System.out.println(hTable.find("abc").getName());
System.out.println(hTable.find("bca").getName());
}
}
我們用冪函數的方式去重寫hashcode
public inthashCode(String key) {int hashValue = 0;int pow27 = 1;for (int i = key.length() - 1; i >= 0; i--) {int letter = key.charAt(i) - 96;
hashValue+= letter *pow27;
pow27*= 27;
}returnhashValue;
}
packagech15;public classTestHashTable {public static voidmain(String[] args) {
HashTable hTable= newHashTable();
hTable.insert(new Info("abc", "張三"));
hTable.insert(new Info("bca", "李四"));
System.out.println(hTable.find("abc").getName());
System.out.println(hTable.find("bca").getName());
}
}
此時可以解決上面的問題,但是浪費太多內存了,因為字符串如果很長,數組容易越界或者內存溢出,因此需要進行取模運算。
public inthashCode(String key) {
BigInteger hashValue= new BigInteger("0");
BigInteger pow27= new BigInteger("1");for (int i = key.length() - 1; i >= 0; i--) {int letter = key.charAt(i) - 96;
BigInteger letterB= newBigInteger(String.valueOf(letter));
hashValue=hashValue.add(letterB.multiply(pow27));
pow27= pow27.multiply(new BigInteger(String.valueOf(27)));
}return hashValue.mod(newBigInteger(String.valueOf(key.length()))).intValue();
}
總結
以上是生活随笔為你收集整理的java数据结构期末复习_java数据结构复习02的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ios开发 多人语音聊天_在 Unity
- 下一篇: 北京大学计算机科学李丰,中文智能问答系统