20192317邓子彦 实验八 《数据结构与面向对象程序设计》实验报告
课程:《程序设计与数据结构》
班级: 1923
姓名: 邓子彦
学号:20192317
实验教师:王志强
实验日期:2020年12月3日
必修/选修: 必修
1. 实验内容
-
1.参考教材PP16.1,完成链树LinkedBinaryTree的实现(getRight,contains,toString,preorder,postorder)
用JUnit或自己编写驱动类对自己实现的LinkedBinaryTree进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台 -
2.基于LinkedBinaryTree,实现基于(中序,先序)序列构造唯一一棵二㕚树的功能,比如给出中序HDIBEMJNAFCKGL和后序ABDHIEJMNCFGKL,构造出附图中的树
用JUnit或自己编写驱动类对自己实现的功能进行测试,提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台 -
3.自己设计并实现一颗决策树
提交测试代码运行截图,要全屏,包含自己的学号信息
课下把代码推送到代码托管平台 -
4.输入中缀表达式,使用树将中缀表达式转换为后缀表达式,并输出后缀表达式和计算结果(如果没有用树,正常评分。如果用到了树,即使有小的问题,也酌情给满分)
提交测试代码运行截图,要全屏,包含自己的学号信息
2. 实验过程及结果
一、实验一
- 通用代码
//BTNode
import java.util.ArrayList;
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 (ArrayList<T> iter) {
if (left != null)
left.inorder (iter);
iter.add (element);
if (right != null)
right.inorder (iter);
}
public void preorder (ArrayList<T> iter) {
iter.add (element);
if (left != null)
left.inorder (iter);
if (right != null)
right.inorder (iter);
}
public void postorder (ArrayList<T> iter) {
if (left != null)
left.inorder (iter);
if (right != null)
right.inorder (iter);
iter.add (element);
}
public char print() {
return (char) element;
}
}
//ElementNotFoundException
public class ElementNotFoundException extends Throwable {
public ElementNotFoundException(String s) {
}
}
//EmptyCollectionException
public class EmptyCollectionException extends Exception {
public EmptyCollectionException(String queue) {
System.out.println(queue);
}
}
//LinearNode
public class LinearNode<T>
{
private LinearNode<T> next;
private T element;
public LinearNode()
{
next = null;
element = null;
}
public LinearNode(T elem) { next = null; element = elem; }
public LinearNode<T> getNext() { return next; }
public void setNext (LinearNode<T> node) { next = node; }
public T getElement() { return element; }
public void setElement (T elem) { element = elem; }
}
//LinkedBinaryTree
import java.util.Iterator;
public class LinkedBinaryTree<T> implements BinaryTree<T> {
public BTNode<T> root;//定义根结点
public BTNode left;
public BTNode right;
public LinkedBinaryTree()
{
root = null;
}//未赋值时,根结点为空
public LinkedBinaryTree(T element)
{
root = new BTNode<T>(element);
}//进行根结点赋值
public LinkedBinaryTree(T element, LinkedBinaryTree<T> left,
LinkedBinaryTree<T> right)//根、左、右、再思考
{
root = new BTNode<T>(element);
root.setLeft(left.root);
root.setRight(right.root);
}
public T getRootElement() throws Exception {
if (root == null)
throw new Exception ("Get root operation "
+ "failed. The tree is empty.");
return root.getElement();
}
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;
}
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();
}
public int size()
{
int result = 0;
if (root != null)
result = root.count();
return result;
}
public Iterator<T> inorder()
{
ArrayIterator<T> iter = new ArrayIterator<T>();
if (root != null)
root.inorder (iter);
return iter;
}
public Iterator<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;
}
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>
";
for(T i : list){
result += i + " ";
}
return result + "<bottom of Tree>";
}
public Iterator<T> preorder() {
ArrayIterator<T> list = new ArrayIterator<>();
if(root!=null)
root.preorder(list);
return list;
}
public Iterator<T> postorder() {
ArrayIterator<T> list = new ArrayIterator<>();
if(root!=null)
root.postorder(list);
return list;
}
@Override
public Iterator<T> iterator() {
return null;
}
}
//LinkedQueue
public class LinkedQueue<T> implements QueueADT<T>
{
private int count;
private LinearNode<T> front, rear;
public LinkedQueue()
{
count = 0;
front = rear = null;
}
public void enqueue (T element)
{
LinearNode<T> node = new LinearNode<T>(element);
if (isEmpty()) front = node;
else rear.setNext (node);
rear = node;
count++;
}
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 third() throws EmptyCollectionException
{
if (isEmpty()) throw new EmptyCollectionException("queue");
return front.getElement();
}
public boolean isEmpty()
{
return (count == 0);
}
public int size()
{
return count;
}
public String toString()
{
String result = "";
LinearNode<T> current = front;
while (current != null)
{
result = result + (current.getElement()).toString() + "
";
current = current.getNext();
}
return result;
}
}
//ArrayIterator
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();
}
}
//BinaryTree
import java.util.Iterator;
public interface BinaryTree<T> extends Iterable<T>
{
public T getRootElement() throws Exception;
public BinaryTree<T> getLeft() throws Exception;
public BinaryTree<T> getRight() throws Exception;
public boolean contains (T target) throws Exception;
public T find (T target) throws Exception;
public boolean isEmpty();
public int size();
public String toString();
public Iterator<T> preorder();
public Iterator<T> inorder();
public Iterator<T> postorder();
public Iterator<T> levelorder() throws Exception;
}
//QueueADT
public interface QueueADT<T>
{
public void enqueue (T element);
public T dequeue() throws EmptyCollectionException;
public T third() throws EmptyCollectionException;
public boolean isEmpty();
public int size();
public String toString();
}
- 1.实验代码
//LinkedBinaryTreeTest
import junit.framework.TestCase;
import org.junit.Test;
public class LinkedBinaryTreeTest 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(20);
LinkedBinaryTree x2 = new LinkedBinaryTree(23);
LinkedBinaryTree x3 = new LinkedBinaryTree(19,x1,x2);
LinkedBinaryTree x4 = new LinkedBinaryTree(17);
LinkedBinaryTree x5 = new LinkedBinaryTree(17,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, 1, 3, 2, 4]",e.preorder().toString());
assertEquals("[3, 1, 2]",c.preorder().toString());
}
public void testPostorder() {//后序
assertEquals("[1, 3, 2, 4, 5]",e.postorder().toString());
assertEquals("[1, 2, 3]",c.postorder().toString());
assertEquals("[20, 19, 23, 17, 17]",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(false,e.contains(17));
assertEquals(false,a.contains(17));
}
public void testIsEmpty() {
assertEquals(false,a.isEmpty());
assertEquals(true,f.isEmpty());
}
}
-
2.运行截图
-
二、实验二
-
1.实验代码
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, 1, 3, 2, 4]",e.preorder().toString());
assertEquals("[3, 1, 2]",c.preorder().toString());
}
public void testPostorder() {//后序
assertEquals("[1, 3, 2, 4, 5]",e.postorder().toString());
assertEquals("[1, 2, 3]",c.postorder().toString());
assertEquals("[20, 19, 23, 17, 17]",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(false,e.contains(17));
assertEquals(false,a.contains(17));
}
public void testIsEmpty() {
assertEquals(false,a.isEmpty());
assertEquals(true,f.isEmpty());
}
-
2.运行截图
-
三、实验三
-
1.实验代码
//Decision
import java.util.Scanner;
public class Decision {
private LinkedBinaryTree<String> tree;
public Decision(){
String e1 = "你喜欢玩游戏吗?";
String e2 = "你喜欢用手机玩游戏吗?";
String e3 = "你很自律,不过偶尔还是要点游戏来放松生活。";
String e4 = "那你玩过王者荣耀吗? ";
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 diagose() throws Exception {
Scanner scan = new Scanner(System.in);
LinkedBinaryTree<String> current = tree;
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());
}
}
//DecisionTest
public class DecisionTest {
public static void main(String[]args) throws Exception {
Decision a = new Decision();
a.diagose();
}
}
-
2.运行截图
-
四、实验四
-
1.实验代码
//Fix
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;
}
}
//FixTest
import java.util.Scanner;
public class FixTest {
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("后缀表达式为:
"+Fix.getrp(s));
System.out.println("计算结果为:
"+fix.calrp(Fix.getrp(s)));
}
}
- 2.运行截图
3. 实验过程中遇到的问题和解决过程
-
问题1:不知道决策树该怎么操作,因为教科书的版本不同,而且书上的代码用了会莫名其妙报错,越做越乱
-
解决办法:上CSDN搜索JAVA实现简单的决策树,看了很多大佬发的代码和做的跟树有关的知识还有教程。还去看了学长学姐的博客,看了一看他们写的代码和截图,了解了这个决策树该怎么操作。
-
问题2:中缀表达式转换为后缀表达式,不知道该怎么实现读取数字和符号,这个小实验点不知道怎么做
-
解决办法:上CSDN搜索JAVA实现中缀表达式的转换,看了很多发帖子的代码和解决思路,又去看了学长学姐的博客还有他们的代码,还是对于这个实验点的实现比较不熟悉不了解,最后询问其他完成的同学该怎么操作,然后才实现了这个实验点。
4. 实验体会
- 树的知识还是不算很牢固,所以实验做起来还是有点艰难。不过这门课的作用就在于让我们遇到困难之后寻找解决的方法,这是难能可贵的一种品质,需要我们从现在开始培养。学期也准备结束了,但是感觉到自己的知识点还是很不牢固,害,还需要继续努力呢!