1. 程式人生 > 實用技巧 >20192328牛梓萌 2019-2020-1 《資料結構與面向物件程式設計》實驗八報告

20192328牛梓萌 2019-2020-1 《資料結構與面向物件程式設計》實驗八報告

20192328牛梓萌 2019-2020-1 《資料結構與面向物件程式設計》實驗八報告

課程:《程式設計與資料結構》
班級: 1923
姓名: 牛梓萌
學號:20192328
實驗教師:王志強
實驗日期:2020年12月3日
必修/選修: 必修

1.實驗內容

1.參考教材PP16.1,完成鏈樹LinkedBinaryTree的實現(getRight,contains,toString,preorder,postorder)
用JUnit或自己編寫驅動類對自己實現的LinkedBinaryTree進行測試,提交測試程式碼執行截圖,要全屏,包含自己的學號資訊
課下把程式碼推送到程式碼託管平臺

2.基於LinkedBinaryTree,實現基於(中序,先序)序列構造唯一一棵二㕚樹的功能,比如給出中序HDIBEMJNAFCKGL和後序ABDHIEJMNCFGKL,構造出附圖中的樹
用JUnit或自己編寫驅動類對自己實現的功能進行測試,提交測試程式碼執行截圖,要全屏,包含自己的學號資訊
課下把程式碼推送到程式碼託管平臺

3.自己設計並實現一顆決策樹
提交測試程式碼執行截圖,要全屏,包含自己的學號資訊
課下把程式碼推送到程式碼託管平臺

4.輸入中綴表示式,使用樹將中綴表示式轉換為字尾表示式,並輸出字尾表示式和計算結果(如果沒有用樹,正常評分。如果用到了樹,即使有小的問題,也酌情給滿分)
提交測試程式碼執行截圖,要全屏,包含自己的學號資訊

2. 實驗過程及結果

1.參考教材PP16.1,完成鏈樹LinkedBinaryTree的實現(getRight,contains,toString,preorder,postorder)

package Exp8_1;

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;

public class ArrayIterator<T> extends ArrayList<T> implements Iterator<T> {

    int iteratorModCount;
    int current;
    public ArrayIterator()
    {
        iteratorModCount = modCount;
        current = 0;

    }
    public boolean hasNext() throws ConcurrentModificationException
    {
        return super.iterator().hasNext();
    }
    public T next() throws ConcurrentModificationException
    {
        return super.iterator().next();
    }
    public void remove() throws UnsupportedOperationException
    {
        throw new UnsupportedOperationException();
    }
}
package Exp8_1;

import java.util.ArrayList;

public interface BinaryTree<T> extends Iterable<T>
{
    //  Returns the element stored in the root of the tree.
    public T getRootElement() throws  Exception;

    //  Returns the left subtree of the root.
    public BinaryTree<T> getLeft() throws  Exception;

    //  Returns the right subtree of the root.
    public BinaryTree<T> getRight() throws Exception;

    //  Returns true if the binary tree contains an element that
    //  matches the specified element and false otherwise.
    public boolean contains (T target) throws Exception;

    //  Returns a reference to the element in the tree matching
    //  the specified target.
    public T find (T target) throws  Exception;

    //  Returns true if the binary tree contains no elements, and
    //  false otherwise.
    public boolean isEmpty();

    //  Returns the number of elements in this binary tree.
    public int size();

    //  Returns the string representation of the binary tree.
    public String toString();

    //  Returns a preorder traversal on the binary tree.
    public ArrayList<T> preorder();

    //  Returns an inorder traversal on the binary tree.
    public ArrayList<T> inorder();

    //  Returns a postorder traversal on the binary tree.
    public ArrayList<T> postorder();

    //  Performs a level-order traversal on the binary tree.
    public ArrayList<T> levelorder() throws Exception;
}
package Exp8_1;

public class BTNode<T> {
    protected T element;
    protected BTNode<T> left, right;
    public BTNode (T element)
    {
        this.element = element;
        left = right = null;
    }
    public T getElement()
    {
        return element;
    }
    public void setElement (T element)
    {
        this.element = element;
    }
    public BTNode<T> getLeft()
    {
        return left;
    }

    public void setLeft (BTNode<T> left)
    {
        this.left = left;
    }

    public BTNode<T> getRight()
    {
        return right;
    }

    public void setRight (BTNode<T> right)
    {
        this.right = right;
    }

    public BTNode<T> find (T target)
    {
        BTNode<T> result = null;

        if (element.equals(target))
            result = this;
        else
        {
            if (left != null)
                result = left.find(target);
            if (result == null && right != null)
                result = right.find(target);
        }

        return result;
    }

    public int count()
    {
        int result = 1;

        if (left != null)
            result += left.count();

        if (right != null)
            result += right.count();

        return result;
    }
    public void inorder ( ArrayIterator<T> iter)
    {
        if (left != null)
            left.inorder (iter);

        iter.add (element);

        if (right != null)
            right.inorder (iter);
    }
    public void preorder ( ArrayIterator<T> iter) {
        iter.add(element);

        if(left!=null)
            left.preorder(iter);

        if (right != null)
            right.preorder(iter);
    }

    public void postorder ( ArrayIterator<T> iter) {
        if(left != null)
            left.postorder(iter);

        if(right != null)
            right.postorder(iter);

        iter.add(element);
    }
    //Exp8_2
    public char print() {return (char) element; }
}
package Exp8_1;

public class EmptyCollectionException extends Exception {

    public EmptyCollectionException(String queue) {
        System.out.println(queue);
    }
}
package Exp8_1;

public class LinearNode<T>{
    private LinearNode<T> next;
    private T element;

    /*
      Creates an empty node.
     */
    public LinearNode()
    {
        next = null;
        element = null;
    }

    /*
      Creates a node storing the specified element.
      @param elem  the element to stored within the created node
     */
    public LinearNode (T elem)
    {
        next = null;
        element = elem;
    }

    /*
      Returns the node that follows this one.
      @return  the node that follows this one
     */
    public LinearNode<T> getNext()
    {
        return next;
    }

    /*
     Sets the node that follows this one.
     @param node  the node to be set as the next node for this node
     */
    public void setNext (LinearNode<T> node)
    {
        next = node;
    }

    /*
     Returns the element stored in this node.
     @return  the element that is stored within this node
     */
    public T getElement()
    {
        return element;
    }

    /*
     Sets the element stored in this node.
     @param elem  the element to be stored within this node
     */
    public void setElement (T elem)
    {
        element = elem;
    }}
package Exp8_1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class LinkedBinaryTree<T> implements BinaryTree<T> {
    public BTNode<T> root;
    //Creates an empty binary tree.
    public BTNode left;
    public BTNode right;

    public LinkedBinaryTree()
    {
        root = null;
    }
    //Creats a binary tree with the specified element as its root.
    public LinkedBinaryTree (T element)
    {
        root = new BTNode<T>(element);
    }
    //Creats a binary tree with the two specified subtrees.
    public LinkedBinaryTree (T element, LinkedBinaryTree<T> left,
                             LinkedBinaryTree<T> right)
    {
        root = new BTNode<T>(element);
        root.setLeft(left.root);
        root.setRight(right.root);
    }
    //Returns the element stored in the root of the tree.
    //Throws an EmptyCollectionException if the tree is empty.
    public T getRootElement() throws Exception {
        if (root == null)
            throw new Exception ("Get root operation "
                    + "failed. The tree is empty.");
        return root.getElement();
    }
    //Returns the left subtree of the root of this tree.
    public LinkedBinaryTree<T> getLeft() throws Exception {
        if (root == null)
            throw new Exception ("Get left operation "
                    + "failed. The tree is empty.");

        LinkedBinaryTree<T> result = new LinkedBinaryTree<T>();
        result.root = root.getLeft();

        return result;
    }
    //Returns the element in this binary tree that matches the specified target.
    //Throws a ElementNotFoundException if the target is not found.
    public T find (T target) throws Exception {
        BTNode<T> node = null;

        if (root != null)
            node = root.find(target);

        if (node == null)
            throw new Exception("Find operation failed. "
                    + "No such element in tree.");

        return node.getElement();
    }
    //Returns the number of elements in this binary tree.
    public int size()
    {
        int result = 0;

        if (root != null)
            result = root.count();

        return result;
    }
    //Populates and returns an iterator containing the elements in this binary tree using an inorder traversal.
    public ArrayIterator<T> inorder()
    {
        ArrayIterator<T> iter = new ArrayIterator<T>();

        if (root != null)
            root.inorder (iter);

        return  iter;
    }
    //Populates and returns an iterator containing the elements in this binary tree using an levelorder traversal.
    public ArrayList<T> levelorder() throws EmptyCollectionException {
        LinkedQueue<BTNode<T>> queue = new LinkedQueue<BTNode<T>>();
        ArrayIterator<T> iter = new  ArrayIterator<T>();

        if (root != null)
        {
            queue.enqueue(root);
            while (!queue.isEmpty())
            {
                BTNode<T> current = queue.dequeue();

                iter.add (current.getElement());

                if (current.getLeft() != null)
                    queue.enqueue(current.getLeft());
                if (current.getRight() != null)
                    queue.enqueue(current.getRight());
            }
        }

        return iter;
    }
    //satisfies the Iterable interface using an inorder traversal.
    public Iterator<T> ArrayIterator()
    {
        return inorder();
    }
    public LinkedBinaryTree<T> getRight() throws Exception {
        if (root == null)
            throw new Exception ("Get Right operation "
                    + "failed. The tree is empty.");
        LinkedBinaryTree<T> result = new LinkedBinaryTree<T>();
        result.root = root.getRight();

        return result;
    }
    public boolean contains (T target) throws Exception {
        BTNode<T> node = null;
        boolean result = true;
        if (root != null)
            node = root.find(target);
        if(node == null)
            result = false;
        return result;
    }
    public boolean isEmpty() {
        if(root!=null)
            return false;
        else
            return true;
    }
    public String toString() {
        ArrayIterator<T> list = (ArrayIterator<T>) preorder();
        String result = "<top of Tree>\n";
        for(T i : list){
            result += i + "\t";
        }
        return result + "<bottom of Tree>";
    }
    public ArrayIterator<T> preorder() {
        ArrayIterator<T> list = new  ArrayIterator<>();

        if(root!=null)
            root.preorder(list);
        return list;
    }

    public ArrayIterator<T> postorder() {
        ArrayIterator<T> list = new  ArrayIterator<>();

        if(root!=null)
            root.postorder(list);
        return list;
    }



    @Override
    public Iterator<T> iterator() {
        return null;
    }
//Exp8_2
    public BTNode construct(char[] pre, char[] in){
        if (pre.length == 0 || in.length == 0) {
            return null;
        }
        BTNode<Character> tree = new BTNode<Character>(pre[0]);
        int index = search(0, in.length, in, tree.getElement());
        tree.setLeft(construct(Arrays.copyOfRange(pre, 1, index + 1), Arrays.copyOfRange(in, 0, index)));
        tree.setRight(construct(Arrays.copyOfRange(pre, index + 1, pre.length),
                Arrays.copyOfRange(in, index + 1, in.length)));
        return tree;
    }
    public int search(int start, int end, char[] inOrders, char data) {
        for (int i = start; i < end; i++) {
            if (data == inOrders[i]) {
                return i;
            }
        }
        return -1;
    }

    public void preOrder(BTNode<T> Tree)
    {
        System.out.print(Tree.getElement()+" ");
        BTNode<T> leftTree = Tree.left;
        if(leftTree != null)
        {
            preOrder(leftTree);
        }
        BTNode<T> rightTree = Tree.right;
        if(rightTree != null)
        {
            preOrder(rightTree);
        }
    }

    public static void postOrder(BTNode tree) {
        if (tree == null)
            return;
        else {
            postOrder(tree.left);
            postOrder(tree.right);
            System.out.print(tree.print() + " ");
        }
    }
    public static void inOrder(BTNode tree) {
        if (tree == null)
            return;
        else {
            inOrder(tree.left);
            System.out.print(tree.print() + " ");
            inOrder(tree.right);

        }
    }
}
package Exp8_1;

public class LinkedQueue<T> implements QueueADT<T>{
    private int count;
    private LinearNode<T> front, rear;

    /*
      Creates an empty queue.
     */
    public LinkedQueue()
    {
        count = 0;
        front = rear = null;
    }

    /*
     Adds the specified element to the rear of this queue.
     @param element  the element to be added to the rear of this queue
     */
    public void enqueue (T element)
    {
        LinearNode<T> node = new LinearNode<T>(element);

        if (isEmpty())
            front = node;
        else
            rear.setNext (node);

        rear = node;
        count++;
    }

    /*
      Removes the element at the front of this queue and returns a
      reference to it. Throws an EmptyCollectionException if the
      queue is empty.
      @return                           the element at the front of this queue
      @throws EmptyCollectionException  if an empty collection exception occurs
     */
    public T dequeue() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException ("queue");

        T result = front.getElement();
        front = front.getNext();
        count--;

        if (isEmpty())
            rear = null;

        return result;
    }

    public T first() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException ("queue");

        return front.getElement();
    }

    /*
     Returns true if this queue is empty and false otherwise.
      @return  true if this queue is empty and false if otherwise
     */
    public boolean isEmpty()
    {
        return (count == 0);
    }

    /*
     Returns the number of elements currently in this queue.
     @return  the integer representation of the size of this queue
     */
    public int size()
    {
        return count;
    }

    /*
      Returns a string representation of this queue.
     @return  the string representation of this queue
     */
    public String toString()
    {
        String result = "";
        LinearNode<T> current = front;

        while (current != null)
        {
            result = result + (current.getElement()).toString() + "\n";
            current = current.getNext();
        }

        return result;
}}
package Exp8_1;

public interface QueueADT<T>
{

    /*
     Adds one element to the rear of this queue.
     @param element  the element to be added to the rear of this queue
     */
    public void enqueue (T element);

    /*
     Removes and returns the element at the front of this queue.
     @return  the element at the front of this queue
     */
    public T dequeue() throws EmptyCollectionException;

    /*
     Returns without removing the element at the front of this queue.
     @return  the first element in this queue
     */
    public T first() throws EmptyCollectionException;

    /*
     Returns true if this queue contains no elements.
     @return  true if this queue is empty
     */
    public boolean isEmpty();

    /*
     Returns the number of elements in this queue.
     @return  the integer representation of the size of this queue
     */
    public int size();

    /*
     Returns a string representation of this queue.
     @return  the string representation of this queue
     */
    public String toString();
}
package Exp8_1;

import junit.framework.TestCase;
import org.junit.Test;

public class Test81 extends TestCase {
    LinkedBinaryTree a = new LinkedBinaryTree(1);
    LinkedBinaryTree b = new LinkedBinaryTree(2);
    LinkedBinaryTree c = new LinkedBinaryTree(3,a,b);
    LinkedBinaryTree d = new LinkedBinaryTree(4);
    LinkedBinaryTree e = new LinkedBinaryTree(5,c,d);
    LinkedBinaryTree f = new LinkedBinaryTree();
    LinkedBinaryTree x1 = new LinkedBinaryTree(28);
    LinkedBinaryTree x2 = new LinkedBinaryTree(23);
    LinkedBinaryTree x3 = new LinkedBinaryTree(19,x1,x2);//學號測試
    LinkedBinaryTree x4 = new LinkedBinaryTree(6);
    LinkedBinaryTree x5 = new LinkedBinaryTree(6,x3,x4);

    @Test
    public void testSize() {
        assertEquals(3,c.size());
        assertEquals(5,e.size());
    }

    public void testInorder() {
        assertEquals("[1, 3, 2, 5, 4]",e.inorder().toString());
        assertEquals("[1, 3, 2]",c.inorder().toString());
    }

    public void testPreorder() {
        assertEquals("[5, 3, 1, 2, 4]",e.preorder().toString());
        assertEquals("[3, 1, 2]",c.preorder().toString());
    }

    public void testPostorder() {
        assertEquals("[1, 2, 3, 4, 5]",e.postorder().toString());
        assertEquals("[1, 2, 3]",c.postorder().toString());
        assertEquals("[28, 23, 19, 6, 6]",x5.postorder().toString());
    }

    public void testLevelorder() throws EmptyCollectionException {
        assertEquals("[5, 3, 4, 1, 2]",e.levelorder().toString());
        assertEquals("[3, 1, 2]",c.levelorder().toString());
    }

    public void testContains() throws Exception {
        assertEquals(true,e.contains(5));
        assertEquals(false,a.contains(6));
    }

    public void testIsEmpty() {
        assertEquals(false,a.isEmpty());
        assertEquals(true,f.isEmpty());
    }

}

執行結果

碼雲:https://gitee.com/besti1923/niu-zimeng-20192328/tree/master/src/Exp8_1

2.基於LinkedBinaryTree,實現基於(中序,先序)序列構造唯一一棵二㕚樹的功能,比如給出中序HDIBEMJNAFCKGL和後序ABDHIEJMNCFGKL,構造出附圖中的樹

在8_1中的BTNode和LinkedBinaryTree新增程式碼

//Exp8_2
    public BTNode construct(char[] pre, char[] in){
        if (pre.length == 0 || in.length == 0) {
            return null;
        }
        BTNode<Character> tree = new BTNode<Character>(pre[0]);
        int index = search(0, in.length, in, tree.getElement());
        tree.setLeft(construct(Arrays.copyOfRange(pre, 1, index + 1), Arrays.copyOfRange(in, 0, index)));
        tree.setRight(construct(Arrays.copyOfRange(pre, index + 1, pre.length),
                Arrays.copyOfRange(in, index + 1, in.length)));
        return tree;
    }
    public int search(int start, int end, char[] inOrders, char data) {
        for (int i = start; i < end; i++) {
            if (data == inOrders[i]) {
                return i;
            }
        }
        return -1;
    }

    public void preOrder(BTNode<T> Tree)
    {
        System.out.print(Tree.getElement()+" ");
        BTNode<T> leftTree = Tree.left;
        if(leftTree != null)
        {
            preOrder(leftTree);
        }
        BTNode<T> rightTree = Tree.right;
        if(rightTree != null)
        {
            preOrder(rightTree);
        }
    }

    public static void postOrder(BTNode tree) {
        if (tree == null)
            return;
        else {
            postOrder(tree.left);
            postOrder(tree.right);
            System.out.print(tree.print() + " ");
        }
    }
    public static void inOrder(BTNode tree) {
        if (tree == null)
            return;
        else {
            inOrder(tree.left);
            System.out.print(tree.print() + " ");
            inOrder(tree.right);

        }
    }
}
  //Exp8_2
    public char print() {return (char) element; }
}
package Exp8_2;

import Exp8_1.BTNode;
import Exp8_1.LinkedBinaryTree;
import java.util.Scanner;
class Exp8_2 {
    public static void main(String[] args) {
        LinkedBinaryTree t = new LinkedBinaryTree();
        BTNode tree;


       char[] pre = {'A','B','D','H','I','E','J','M','N','C','F','G','K','L'};
        char[] in = {'H','D','I','B','E','M','J','N','A','F','C','K','G','L'};
        tree = t.construct(pre,in);

        System.out.println("先序遍歷");
        t.preOrder(tree);
        System.out.println("\n中序遍歷");
        t.inOrder(tree);
        System.out.println("\n後序遍歷");
        t.postOrder(tree);
    }
}

執行結果

碼雲:https://gitee.com/besti1923/niu-zimeng-20192328/tree/master/src/Exp8_2和https://gitee.com/besti1923/niu-zimeng-20192328/tree/master/src/Exp8_1

3.自己設計並實現一顆決策樹

package Exp8_3;

import Exp8_1.LinkedBinaryTree;

import java.util.Scanner;

public class Expert {
    private LinkedBinaryTree<String> tree;

    public Expert(){
        String e1 = "你學渾元形意太極門嗎?";
        String e2 = "你講武德麼?";
        String e3 = "再見。";
        String e4 = "你有bear來嗎?";
        String e5 = "拳頭放在你鼻子上!武林要以和為貴。";
        String e6 = "鐺鐺!一個右鞭腿、一個左刺拳,全部被你防住防出去了!";
        String e7 = "年輕人耗子尾汁!";

        LinkedBinaryTree<String> n2,n3,n4,n5,n6,n7;
        n3 = new LinkedBinaryTree<String>(e3);
        n5 = new LinkedBinaryTree<String>(e5);
        n6 = new LinkedBinaryTree<String>(e6);
        n7 = new LinkedBinaryTree<String>(e7);
        n4 = new LinkedBinaryTree<String>(e4,n6,n7);
        n2 = new LinkedBinaryTree<String>(e2,n4,n5);

        tree = new LinkedBinaryTree<String>(e1,n2,n3);
    }

    public void diagnose() throws Exception {
        Scanner scan = new Scanner(System.in);
        LinkedBinaryTree<String> current = tree;

        System.out.println("Hello!歡迎進入渾元形意太極的世界");
        while(current.size()>1)
        {
            System.out.println(current.getRootElement());
            if(scan.nextLine().equalsIgnoreCase("Y"))
                current = current.getLeft();
            else
                current = current.getRight();
        }
        System.out.println(current.getRootElement());
    }
}
package Exp8_3;

public class Test83 {
    public static void main(String[] args) throws Exception {
        Expert expert = new Expert();
        expert.diagnose();
    }
}

執行結果

碼雲:https://gitee.com/besti1923/niu-zimeng-20192328/tree/master/src/Exp8_3和https://gitee.com/besti1923/niu-zimeng-20192328/tree/master/src/Exp8_1

4.輸入中綴表示式,使用樹將中綴表示式轉換為字尾表示式,並輸出字尾表示式和計算結果

package Exp8_4;

import java.util.Scanner;

public class Exp8_4 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("請輸入表示式:");
        String s = scan.nextLine();
        Fix fix = new Fix();
        System.out.println("字尾表示式為:\n"+Fix.getrp(s));
        System.out.println("計算結果為:\n"+fix.calrp(Fix.getrp(s)));
    }
}
package Exp8_4;

import java.util.Stack;

public class Fix {
    static Stack<Character> op = new Stack<>();

    public static Float getv(char op, Float f1, Float f2) {
        if (op == '+') return f2 + f1;
        else if (op == '-') return f2 - f1;
        else if (op == '*') return f2 * f1;
        else if (op == '/') return f2 / f1;
        else return Float.valueOf(-0);
    }

    public static float calrp(String rp) {
        Stack<Float> v = new Stack<>();
        char[] arr = rp.toCharArray();
        int len = arr.length;
        for (int i = 0; i < len; i++) {
            Character ch = arr[i];
            if (ch >= '0' && ch <= '9') v.push(Float.valueOf(ch - '0'));
            else v.push(getv(ch, v.pop(), v.pop()));
        }
        return v.pop();
    }

    public static String getrp(String s) {
        char[] arr = s.toCharArray();
        int len = arr.length;
        String out = "";

        for (int i = 0; i < len; i++) {
            char ch = arr[i];
            if (ch == ' ') continue;
            if (ch >= '0' && ch <= '9') {
                out += ch;
                continue;
            }

            if (ch == '(')
                op.push(ch);

            if (ch == '+' || ch == '-') {
                while (!op.empty() && (op.peek() != '('))
                    out += op.pop();
                op.push(ch);
                continue;
            }

            if (ch == '*' || ch == '/') {
                while (!op.empty() && (op.peek() == '*' || op.peek() == '/'))
                    out += op.pop();
                op.push(ch);
                continue;
            }

            if (ch == ')') {
                while (!op.empty() && op.peek() != '(')
                    out += op.pop();
                op.pop();
                continue;
            }
        }
        while (!op.empty()) out += op.pop();
        return out;
    }
}

執行結果

碼雲:https://gitee.com/besti1923/niu-zimeng-20192328/tree/master/src/Exp8_4

其他(感悟、思考等)

現在的學習慢慢和以前學的課程知識融入在一起,之前的程式碼進行修改和新增,需要將知識都聯絡起來,融會貫通。
在寫程式碼之前應該先構思清楚再下手比較方便,不需要大量修改。

參考資料

《Java程式設計與資料結構教程(第二版)》

《Java程式設計與資料結構教程(第二版)》學習指導

...