This commit is contained in:
louiscklaw
2025-01-31 19:15:17 +08:00
parent 09adae8c8e
commit 6c60a73f30
1546 changed files with 286918 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
## Getting Started
Welcome to the VS Code Java world. Here is a guideline to help you get started to write Java code in Visual Studio Code.
## Folder Structure
The workspace contains two folders by default, where:
- `src`: the folder to maintain sources
- `lib`: the folder to maintain dependencies
Meanwhile, the compiled output files will be generated in the `bin` folder by default.
> If you want to customize the folder structure, open `.vscode/settings.json` and update the related settings there.
## Dependency Management
The `JAVA PROJECTS` view allows you to manage your dependencies. More details can be found [here](https://github.com/microsoft/vscode-java-dependency#manage-dependencies).

View File

@@ -0,0 +1,7 @@
public interface Comparator {
public abstract boolean isEqualTo(Object item1, Object item2);
public abstract boolean isLessThan(Object item1, Object item2);
public abstract boolean isLessThanOrEqualTo(Object item1, Object item2);
public abstract boolean isGreaterThan(Object item1, Object item2);
public abstract boolean isGreaterThanOrEqualTo(Object item1, Object item2);
}

View File

@@ -0,0 +1,54 @@
public class ComparatorLinkedList extends LinkedList {
Comparator comparator;
ComparatorLinkedList(Comparator comparator) {
super();
this.comparator = comparator;
}
public void removeItem(Object item) throws ItemNotFoundException, EmptyListException {
if (isEmpty()) {
throw new ItemNotFoundException();
}
if (comparator.isEqualTo(head.data, item)) {
removeFromHead();
} else if (comparator.isEqualTo(tail.data, item)) {
removeFromTail();
} else {
ListNode current = head;
while (current.next != null) {
if (comparator.isEqualTo(current.next.data, item)) {
current.next = current.next.next;
return;
}
current = current.next;
}
throw new EmptyListException();
}
}
public void insertInOrder(Object item) {
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
if (comparator.isGreaterThanOrEqualTo(head.data, item)) {
addToHead(item);
} else if (comparator.isLessThanOrEqualTo(tail.data, item)) {
addToTail(item);
} else {
ListNode current = head;
while (current.next != null) {
if (comparator.isGreaterThanOrEqualTo(current.next.data, item)) {
ListNode newNode = new ListNode(item);
newNode.next = current.next;
current.next = newNode;
return;
}
current = current.next;
}
}
}
}
}

View File

@@ -0,0 +1,80 @@
public class DoublyList {
private DoublyNode head;
private DoublyNode tail;
public DoublyList() {
head = tail = null;
}
public boolean isEmpty() {
return (head == null);
}
public void addToHead(Object item) {
if (isEmpty()) {
head = tail = new DoublyNode(item);
} else {
head.previous = new DoublyNode(item, null, head);
head = head.previous;
}
}
public void addToTail(Object item) {
if (isEmpty()) {
head = tail = new DoublyNode(item);
} else {
tail.next = new DoublyNode(item, tail, null);
tail = tail.next;
}
}
public Object removeFromHead() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = head.data;
if (head == tail) {
head = tail = null;
} else {
head = head.next;
head.previous = null;
}
return item;
}
public Object removeFromTail() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = tail.data;
if (head == tail) {
head = tail = null;
} else {
tail = tail.previous;
tail.next = null;
}
return item;
}
public String toString(){
String s ="[";
DoublyNode current = head;
while(current!=null){
s+=current.data + " ";
current = current.next;
}
return s + "]";
}
public String forward(){
return toString();
}
public String backward(){
String s = "[";
DoublyNode current =tail;
while(current != null){
s+= current.data + " ";
current = current.previous;
}
return s+ "]";
}
}

View File

@@ -0,0 +1,19 @@
public class DoublyNode {
Object data;
DoublyNode previous;
DoublyNode next;
DoublyNode(Object data){
this.data = data;
previous = next = null;
}
DoublyNode(Object data, DoublyNode previous, DoublyNode next){
this.data = data;
this.previous = previous;
this.next = next;
}
}

View File

@@ -0,0 +1,5 @@
public class EmptyListException extends Exception{
EmptyListException(){
super();
}
}

View File

@@ -0,0 +1,7 @@
public class ItemNotFoundException extends Exception {
ItemNotFoundException(){
super();
}
}

View File

@@ -0,0 +1,158 @@
public class LinkedList {
ListNode head;
ListNode tail;
int count = 0;
LinkedList(){
head = null;
tail = null;
}
public int getCount(){
return count;
}
public boolean isEmpty(){
return (head == null && tail == null);
}
public void addToHead(Object data){
ListNode node = new ListNode(data);
if(isEmpty()){
head = tail = node;
count++;
return;
}
node.next = head;
head = node;
count++;
}
public void addToTail(Object data){
ListNode node = new ListNode(data);
if(isEmpty()){
head = tail = node;
count++;
return;
}
tail.next = node;
tail = node;
count++;
}
public Object removeFromHead(){
if(isEmpty())
throw new IndexOutOfBoundsException();
ListNode node = head;
if(tail == head){
head = tail = null;
count--;
return node.data;
}
head = head.next;
count--;
return node.data;
}
public Object removeFromTail(){
if(isEmpty())
throw new IndexOutOfBoundsException();
ListNode node = tail;
if(tail == head){
head = tail = null;
count--;
return node.data;
}
ListNode currentNode = head;
while(currentNode.next != tail){
currentNode = currentNode.next;
System.out.println(currentNode.data);
}
currentNode.next = null;
tail = currentNode;
count--;
return node.data;
}
public String toString(){
ListNode currentNode = head;
String listData = "";
while (currentNode != null){
listData += currentNode.data + " ";
currentNode = currentNode.next;
}
return listData;
}
public void clear(){
head = tail = null;
}
public Object getItemAt(int n){
if (n < 0 || n >= count)
throw new IndexOutOfBoundsException();
int currentPos = 0;
ListNode currentNode = head;
while(currentPos < n){
if(count == currentPos)
break;
currentNode = currentNode.next;
currentPos++;
}
return currentNode.data;
}
public Object removeItemAt(int n){
if (n < 0 || n >= count)
throw new IndexOutOfBoundsException();
int currentPos = 0;
ListNode currentNode = head;
if(n==0){
removeFromHead();
return currentNode.data;
}
while(currentPos < n-1){
currentNode = currentNode.next;
currentPos++;
}
ListNode item = currentNode.next;
currentNode.next = currentNode.next.next;
count--;
return item.data;
}
public void addItemAt(Object item, int n){
if (n > count)
throw new IndexOutOfBoundsException();
if (isEmpty() || n == 0){
addToHead(item);
return;
}
ListNode node = new ListNode(item);
int currentPos = 0;
ListNode currentNode = head;
while(currentPos < n-1){
currentNode = currentNode.next;
currentPos++;
}
node.next = currentNode.next;
currentNode.next = node;
count++;
}
}

View File

@@ -0,0 +1,14 @@
public class ListNode {
Object data;
ListNode next;
ListNode(Object data, ListNode next){
this.data = data;
this.next = next;
}
ListNode(Object data){
this.data = data;
this.next = null;
}
}

View File

@@ -0,0 +1,17 @@
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String toString() {
return "(" + name + ", " + age + ")";
}
}

View File

@@ -0,0 +1,28 @@
public class PersonComparator implements Comparator {
public boolean isEqualTo(Object item1, Object item2) {
return (((Person) item1).getAge()==((Person) item2).getAge());
}
public boolean isLessThan(Object item1, Object item2) {
return (((Person) item1).getAge()<((Person) item2).getAge());
}
public boolean isLessThanOrEqualTo(Object item1, Object item2) {
return(isLessThan(item1, item2) || isEqualTo(item1, item2));
}
public boolean isGreaterThan(Object item1, Object item2) {
return (((Person) item1).getAge()>((Person) item2).getAge());
}
public boolean isGreaterThanOrEqualTo(Object item1, Object item2) {
return (isGreaterThan(item1, item2) || isEqualTo(item1, item2));
}
}

View File

@@ -0,0 +1,22 @@
public class StringComparator implements Comparator{
public boolean isEqualTo(Object item1, Object item2) {
return ((String) item1).compareTo((String) item2) == 0;
}
public boolean isLessThan(Object item1, Object item2) {
return((String) item1).compareTo((String) item2) < 0;
}
public boolean isLessThanOrEqualTo(Object item1, Object item2) {
return (isEqualTo(item1, item2) || isLessThan(item1, item2));
}
public boolean isGreaterThan(Object item1, Object item2) {
return (((String) item1).compareTo((String) item2) > 0);
}
public boolean isGreaterThanOrEqualTo(Object item1, Object item2) {
return (isEqualTo(item1, item2) || isGreaterThan(item1, item2));
}
}

View File

@@ -0,0 +1,45 @@
public class Test {
public static void main(String[] args) {
LinkedList s = new LinkedList();
System.out.println(s);
s.addToHead("Betty");
s.addToTail("Dave");
s.addToTail("Felix");
s.addToTail("Jenny");
System.out.println(s);
System.out.println("count = " + s.getCount());
System.out.println("Pos 0 = " + s.getItemAt(0));
System.out.println("Pos 2 = " + s.getItemAt(2));
System.out.println("Last = " + s.getItemAt(s.getCount() - 1));
s.addItemAt("Gary", 3);
System.out.println(s);
s.addItemAt("Apple", 0);
System.out.println(s);
System.out.println("Removing " + s.removeItemAt(2));
System.out.println(s);
System.out.println("Removing " + s.removeItemAt(0));
System.out.println(s);
System.out.println("Removing " + s.removeItemAt(3));
System.out.println(s);
// Comparator c = new StringComparator();
// ComparatorLinkedList s = new ComparatorLinkedList(c);
// System.out.println(s);
// s.insertInOrder("Betty");
// System.out.println(s);
// s.insertInOrder("Dave");
// System.out.println(s);
// s.insertInOrder("Catherine");
// System.out.println(s);
// s.insertInOrder("Thomas-1");
// System.out.println(s);
// s.insertInOrder("Sandra");
// System.out.println(s);
// s.insertInOrder("Thomas-2");
// System.out.println(s);
// s.insertInOrder("Alice-1");
// System.out.println(s);
// s.insertInOrder("Alice-2");
// System.out.println(s);
}
}

View File

@@ -0,0 +1,25 @@
public class TestDoubkyList {
public static void main(String[] args) throws EmptyListException {
DoublyList s = new DoublyList();
System.out.println(s);
s.addToTail(1);
System.out.println(s);
s.addToTail(2);
System.out.println(s);
s.addToTail(3);
System.out.println(s);
s.addToHead(0);
System.out.println(s.forward());
System.out.println(s.backward());
while (!s.isEmpty()) {
System.out.println("removed: " + s.removeFromHead());
System.out.println(s);
}
}
}

View File

@@ -0,0 +1,189 @@
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestLinkedList {
private LinkedList list;
@Before
public void init(){
list = new LinkedList();
}
@After
public void teardown(){
list.clear();
}
@Test
public void testAddToHead1(){
list.addToHead("1");
assertEquals(list.toString().trim(), "1");
assertEquals(list.count, 1);
}
@Test
public void testAddToHead2(){
list.addToHead("3");
list.addToHead("2");
list.addToHead("1");
assertEquals(list.toString().trim(), "1 2 3");
}
@Test
public void testAddToTail1(){
list.addToTail("1");
list.addToTail("2");
list.addToTail("3");
assertEquals(list.toString().trim(), "1 2 3");
}
@Test
public void testAddToTail2(){
list.addToTail("1");
assertEquals(list.toString().trim(), "1");
assertEquals(list.count, 1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRemoveFromTail1(){
list.removeFromTail();
}
@Test
public void testRemoveFromTail2(){
list.addToTail(1);
list.removeFromTail();
assertEquals(list.count, 0);
assertEquals(list.toString().trim(), "");
}
@Test
public void testRemoveFromTail3(){
list.addToTail("1");
list.addToTail("2");
list.addToTail("3");
list.addToTail("4");
list.addToHead("0");
list.removeFromTail();
Object data = list.removeFromTail();
assertEquals(data.toString(), "3");
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRemoveFromHead1() {
list.removeFromHead();
}
@Test
public void testRemoveFromHead2() {
list.addToHead("3");
list.addToHead("2");
list.addToHead("1");
list.addToHead("0");
Object data = list.removeFromHead();
assertEquals(data.toString(), "0");
}
@Test
public void testRemoveFromHead3(){
list.addToTail("1");
list.addToHead("0");
list.addToTail("2");
list.removeFromHead();
list.removeFromHead();
list.removeFromHead();
assertEquals(list.toString().trim(), "");
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetItemAt1(){
list.getItemAt(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testGetItemAt2(){
list.getItemAt(1);
}
@Test
public void testGetItemAt3(){
list.addToTail(1);
assertEquals(list.getItemAt(0), 1);
}
@Test
public void testGetItemAt4(){
list.addToTail(1);
list.addToTail(2);
list.addToTail(3);
list.addToTail(4);
list.removeFromTail();
assertEquals(list.getItemAt(2), 3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRemoveItemAt1(){
list.removeItemAt(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testRemoveItemAt2(){
list.removeItemAt(1);
}
@Test
public void testRemoveItemAt3(){
list.addToTail(1);
assertEquals(list.removeItemAt(0), 1);
assertEquals(list.count, 0);
}
@Test
public void testRemoveItemAt4(){
list.addToTail(1);
list.addToTail(2);
list.addToTail(3);
list.addToTail(4);
assertEquals(list.removeItemAt(2), 3);
assertEquals(list.count, 3);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testAddItemAt1(){
System.out.println(list.count);
list.addItemAt(1, 1);
}
@Test
public void testAddItemAt2(){
list.addItemAt(1, 0);
assertEquals(list.count, 1);
assertEquals(list.toString().trim(), "1");
}
@Test
public void testAddItemAt3(){
list.addItemAt(2, 0);
list.addItemAt(1, 0);
assertEquals(list.count, 2);
assertEquals(list.toString().trim(), "1 2");
}
@Test
public void testAddItemAt4(){
list.addToTail(1);
list.addItemAt(2, 1);
list.addItemAt(3, 2);
list.addItemAt(4, 3);
assertEquals(list.count, 4);
assertEquals(list.toString().trim(), "1 2 3 4");
}
}

View File

@@ -0,0 +1,19 @@
public class TestPerson {
public static void main(String[] args) throws ItemNotFoundException, EmptyListException {
Comparator c = new PersonComparator();
ComparatorLinkedList s = new ComparatorLinkedList(c);
System.out.println(s);
s.insertInOrder(new Person("Betty", 21));
System.out.println(s);
s.insertInOrder(new Person("Sandra", 19));
System.out.println(s);
s.insertInOrder(new Person("Alice", 32));
System.out.println(s);
s.insertInOrder(new Person("John", 15));
System.out.println(s);
s.insertInOrder(new Person("Kenneth", 19));
System.out.println(s);
s.removeItem(new Person("unknown", 15));
System.out.println(s);
}
}

View File

@@ -0,0 +1,47 @@
public class ArrayStack implements Stack {
public static final int CAPACITY =1000;
private int capacity;
private Object[] array;
private int top =-1;
public ArrayStack() {
this(CAPACITY);
}
public ArrayStack(int cap){
capacity =cap;
array = new Object[capacity];
}
@Override
public int size() {
return top+1;
}
@Override
public boolean isEmpty() {
return (top<0);
}
@Override
public void push(Object item) throws StackFullException {
if(size()==capacity)
throw new StackFullException();
array[++top]=item;
}
@Override
public Object pop() throws StackEmptyException {
if(isEmpty())
throw new StackEmptyException();
Object item =array[top];
array[top--]=null;
return item;
}
@Override
public Object top() throws StackEmptyException {
if(isEmpty())
throw new StackEmptyException ();
return array[top];
}
}

View File

@@ -0,0 +1,6 @@
class EmptyListException extends Exception {
public EmptyListException() {
}
}

View File

@@ -0,0 +1,101 @@
import java.util.Scanner;
public class EvaPostfix {
public static void main(String[] args) {
Stack s = new LinkedStack();
Scanner keyboard = new Scanner(System.in);
System.out.print("Input the infix expression? ");
String exp = keyboard.nextLine();
try {
if (parenthesisMatching(exp)) {
for (int i = 0; i < exp.length(); i++) {
char item = exp.charAt(i);
if (item == '(' || item == '{' || item == '[') {
s.push(item);
} else if (isOperater(item)) {
if (s.isEmpty()) {
s.push(item);
} else if ((checkVal(item) == checkVal((char) s.top())) || (checkVal(item) < checkVal((char) s.top()))) {
System.out.print(s.pop());
if(s.isEmpty()){
s.push(item);
}else if(checkVal((char) s.top()) == checkVal(item)) {
while (checkVal(item) == checkVal((char) s.top())) {
System.out.print(s.pop());
if (s.isEmpty()) {
s.push(item);
break;
}
}
} else {
s.push(item);
}
} else if (checkVal(item) > checkVal((char) s.top())) {
s.push(item);
}
} else if (item == ')' || item == ']' || item == '}') {
while (((char) s.top() != '(')&&((char) s.top() != '{') && ((char) s.top() != '[')) {
System.out.print(s.pop());
}
s.pop();
} else {
System.out.print(item);
}
}
while (!s.isEmpty()) {
System.out.print(s.pop());
}
} else {
System.out.println("Error");
}
} catch (StackEmptyException e) {
System.out.println("Parenthesis not matched");
} catch (StackFullException e) {
System.out.println("Parenthesis not matched");
}
}
public static boolean parenthesisMatching(String exp) throws StackFullException, StackEmptyException {
Stack s = new LinkedStack();
char item;
for (int i = 0; i < exp.length(); i++) {
item = exp.charAt(i);
if (item == '{' || item == '(' || item == '[') {
s.push(item);
} else if (item == '}' || item == ')' || item == ']') {
char x = (char) s.pop();
if ((x != '(') && (x != '[') && (x != '{')) {
return false;
}
}
}
if (s.isEmpty()) {
return true;
} else {
return false;
}
}
public static boolean isOperater(char exp) {
switch (exp) {
case '+':
case '-':
case '*':
case '/':
return true;
default:
return false;
}
}
public static int checkVal(char exp) {
if (exp == '*' || exp == '/') {
return 5;
} else if (exp == '+' || exp == '-') {
return 3;
} else {//'('
return -1;
}
}
}

View File

@@ -0,0 +1,132 @@
public class LinkedList {
private ListNode head;
private ListNode tail;
private int count = 0;
public boolean isEmpty() {
return (head == null);
}
public void addToHead(Object item) {
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
head = new ListNode(item, head);
}
count++;
}
public void addToTail(Object item) {
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
tail.next = new ListNode(item);
tail = tail.next;
}
count++;
}
public Object removeFromHead() throws EmptyListException {
Object item = null;
if (isEmpty()) {
throw new EmptyListException();
}
item = head.data;
if (head == tail) {
head = tail = null;
} else {
head = head.next;
}
count--;
return item;
}
public Object removeFromtail() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = tail.data;
if (head == tail) {
head = tail = null;
return item;
}
ListNode current = head;
while (current.next != tail) {
current = current.next;
}
tail = current;
tail.next = null;
count--;
return item;
}
public String toString() {
String s = "[ ";
ListNode current = head;
while (current != null) {
s = s + current.data + " ";
current = current.next;
}
return s + " ]";
}
public int getCount() {
return count;
}
public Object getItemAt(int n) {
if (n < 0 || n >= count) {
throw new IndexOutOfBoundsException();
}
int currentPos = 0;
ListNode current = head;
while (currentPos <= (n - 1)) {
current = current.next;
currentPos++;
}
return current.data;
}
public void addItemAt(Object item, int n) {
if (isEmpty() || n == 0) {
addToHead(item);
return;
}
if (n >= count) {
addToTail(item);
return;
}
int currentPos = 0;
ListNode current = head;
while (currentPos < (n - 1)) {
current = current.next;
currentPos++;
}
ListNode newNode = new ListNode(item);
newNode.next = current.next;
current.next = newNode;
count++;
}
public Object removeItemAt(int n) throws EmptyListException{
if(n<0 || n>=count)
throw new IndexOutOfBoundsException();
if(n==0)
removeFromHead();
int currentPos=0;
ListNode current=head;
while(currentPos<(n-1)){
current = current.next;
currentPos++;
}
Object item = current.next.data;
current.next = current.next.next;
count--;
return item;
}
}

View File

@@ -0,0 +1,39 @@
public class LinkedStack implements Stack {
private LinkedList sll = new LinkedList();
@Override
public int size() {
return sll.getCount();
}
@Override
public boolean isEmpty() {
return sll.isEmpty();
}
@Override
public void push(Object item) throws StackFullException {
sll.addToHead(item);
}
@Override
public Object pop() throws StackEmptyException {
try {
Object item = sll.removeFromHead();
return item;
} catch (EmptyListException e) {
throw new StackEmptyException();
}
}
@Override
public Object top() throws StackEmptyException {
try {
Object item = sll.removeFromHead();
sll.addToHead(item);
return item;
} catch (EmptyListException e) {
throw new StackEmptyException();
}
}
}

View File

@@ -0,0 +1,13 @@
public class ListNode {
public Object data;
public ListNode next;
public ListNode(Object ListNode){
this.data = ListNode;
this.next = null;
}
public ListNode(Object ListNode, ListNode next){
this.data = ListNode;
this.next = next;
}
}

View File

@@ -0,0 +1,44 @@
import java.util.Scanner;
public class ParenthesisMatching {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Expression? ");
String exp = keyboard.nextLine();
try {
if (parenthesisMatching(exp)) {
System.out.println("Parenthes is matched");
} else {
System.out.println("Parenthesis not matched");
}
} catch (StackEmptyException e) {
System.out.println("Parenthesis not matched");
} catch (StackFullException e) {
System.out.println("Parenthesis not matched");
}
keyboard.close();
}
public static boolean parenthesisMatching(String exp) throws StackFullException, StackEmptyException {
Stack s = new LinkedStack();
char item;
for (int i = 0; i < exp.length(); i++) {
item = exp.charAt(i);
if (item == '{' || item == '(' || item == '[') {
s.push(item);
} else if (item == '}' || item == ')' || item == ']') {
char x = (char) s.pop();
if ((x != '(') && (x != '[') && (x != '{')) {
return false;
}
}
}
if (s.isEmpty()) {
return true;
} else {
return false;
}
}
}

View File

@@ -0,0 +1,16 @@
public class Reverse {
public static void main(String [ ] args) throws StackFullException, StackEmptyException {
String [ ] arr = {"Abby", "Boris", "Cat", "Dino", "Elvis"};
Stack stack = new ArrayStack();
for (int i=0; i<arr.length; i++) {
stack.push(arr[i]);
}
for (int i=0; i<arr.length; i++) {
arr[i] = (String) stack.pop();
}
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}

View File

@@ -0,0 +1,7 @@
public interface Stack {
public abstract int size();
public abstract boolean isEmpty();
public abstract void push(Object item) throws StackFullException;
public abstract Object pop() throws StackEmptyException;
public abstract Object top() throws StackEmptyException;
}

View File

@@ -0,0 +1,3 @@
public class StackEmptyException extends Exception {
}

View File

@@ -0,0 +1,3 @@
public class StackFullException extends Exception {
}

View File

@@ -0,0 +1,59 @@
public class ArrayQueue {
public static final int CAPACITY = 1000;
private int capacity;
private Object[] array;
private int front = 0;
private int rear = 0;
public ArrayQueue() {
this(CAPACITY);
}
public ArrayQueue(int cap) {
capacity = cap;
array = new Object[capacity];
}
public int size() {
return (capacity - front + rear) % capacity;
}
public boolean isEmpty() {
return (front == rear);
}
public void enqueue(Object item) throws QueueFullException {
if (size() == capacity - 1) {
throw new QueueFullException();
}
array[rear] = item;
rear = (rear + 1) % capacity;
}
public Object dequeue() throws QueueEmptyException {
if (isEmpty()) {
throw new QueueEmptyException();
}
Object item = array[front];
array[front] = null;
front = (front + 1) % capacity;
return item;
}
public Object front() throws QueueEmptyException {
if (isEmpty()) {
throw new QueueEmptyException();
}
return array[front];
}
public String toString() {
String s = "[ ";
int next = front;
for (int i = 0; i < size(); i++) {
s += array[next] + " ";
next = front + i;
}
return s + " ]";
}
}

View File

@@ -0,0 +1,5 @@
public class EmptyListException extends RuntimeException {
public EmptyListException() {
super("List is empty.");
}
}

View File

@@ -0,0 +1,88 @@
public class LinkedList {
private ListNode head;
private ListNode tail;
private int count;
public LinkedList() {
head = null;
tail = null;
count = 0;
}
public boolean isEmpty() {
return (head==null);
}
public int getCount() {
return count;
}
public void addToHead(Object item) {
count++;
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
head = new ListNode(item, head);
}
}
public void addToTail(Object item) {
count++;
if (isEmpty()) {
head = tail = new ListNode(item);
} else {
tail.next = new ListNode(item);
tail = tail.next;
}
}
public Object removeFromHead() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
Object item = head.data;
if (head == tail) // there's only one single node
head = tail = null;
else
head = head.next;
count--;
return item;
}
public Object removeFromTail() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
count--;
Object item = tail.data;
if (head == tail) { // there is only one node
head = tail = null;
return item;
}
// search for the second last node
ListNode current = head;
while (current.next != tail)
current = current.next;
// set second last node as new tail
tail = current;
tail.next = null;
return item;
}
public String toString() {
String s = "[ ";
// traverse the list from head towards tail
ListNode current = head;
while (current != null) {
s += current.data + " ";
current = current.next;
}
return s + "]";
}
}

View File

@@ -0,0 +1,42 @@
public class LinkedQueue {
LinkedList qll;
public LinkedQueue() {
qll = new LinkedList();
}
public int size() {
return qll.getCount();
}
public boolean isEmpty() {
return qll.isEmpty();
}
public void enqueue(Object item) throws QueueFullException {
qll.addToTail(item);
}
public Object dequeue() throws QueueEmptyException {
try {
Object item = qll.removeFromHead();
return item;
} catch (EmptyListException e) {
throw new QueueEmptyException();
}
}
public String toString() {
return qll.toString();
}
public Object front() throws QueueEmptyException {
try {
Object item = qll.removeFromHead();
qll.addToHead(item);
return item;
} catch (EmptyListException e) {
throw new QueueEmptyException();
}
}
}

View File

@@ -0,0 +1,17 @@
public class ListNode {
public Object data; // set to public for implementation convenience
public ListNode next;
public ListNode(Object data) {
this.data = data;
this.next = null;
}
public ListNode(Object data, ListNode next) {
this.data = data;
this.next = next;
}
}

View File

@@ -0,0 +1,7 @@
public interface Queue {
public abstract boolean isEmpty();
public abstract int size();
public abstract Object front() throws QueueEmptyException;
public abstract void enqueue(Object item) throws QueueFullException;
public abstract Object dequeue() throws QueueEmptyException;
}

View File

@@ -0,0 +1,5 @@
public class QueueEmptyException extends Exception{
}

View File

@@ -0,0 +1,5 @@
public class QueueFullException extends Exception{
}

View File

@@ -0,0 +1,17 @@
### Q3
In topic “3.1 Linked Lists”, we have discussed the importance of using a tail for referencing the last node in a linked list. The purpose of this exercise is to have an empirical study on the impact of using the tail reference on a linked list.
Execute the program multiple times with different value for <num>. Record the execution
time as reported by the program in a spreadsheet.
(b) Copy your programs in Q3(a) to a new folder. Q3(b). Modify the Java program LinkedList.java so that the linked list does not contain the tail reference. Needless to say, when the last node in the linked list is wanted, you need to traverse the list from the head towards its end until the last node is reached. Execute LinkedQueueTiming again using the same set of <num> values as in Q3(a). Record the execution time as reported by the program in the spreadsheet.
| n | num | with tail Q3(a) | average time(with tail) | waithout tail Q3(b) | average time(without tail) |
| --- | --- | --- | --- | --- | --- |
| 1 | 10 | 266800 | 276500 | 272300 | 294200 |
| 2 | 100 | 281600 | 288650 | 325500 | 345600 |
| 3 | 1000| 669900 | 671020 | 1767600 | 1678600 |
| 4 | 10000 | 1575200 | 1595300 | 90549600 | 101132100 |
| 5 | 100000 | 5840900 | 6020100 | 9229402000 | 9103203100 |
| 6 | 1000000 | 24357800 | 26236800 | 1500203112900 | 1612141023950 |

View File

@@ -0,0 +1,32 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BstTiming {
public static void main(String[] args) {
try {
StringBst tree = new StringBst();
Scanner fin = new Scanner(new File(args[0]));
String line;
while (fin.hasNextLine()) {
line = fin.nextLine();
line = line.trim();
tree.addNode(line);
}
fin.close();
long startTime = System.nanoTime();
String ans = tree.search(args[1]);
long endTime = System.nanoTime();
if (ans==null)
System.out.println("Not found; Time used: " + (endTime - startTime));
else
System.out.println("Found; Time used: " + (endTime - startTime));
}
catch (FileNotFoundException e) {
System.out.println("Failed to open " + args[0]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: BstTiming <word_file> <search_word>");
}
}
}

View File

@@ -0,0 +1,240 @@
### Q2(c)
Now, perform some experiments to test the searching performance in the two approaches. Record the results in the table below. You are free to try some more words.
| Word to search for | Result (found/ not found) | Time needed (BST) | Time needed (linked list)
| --- | --- | --- | --- |
| water | Found | 2500 | 7100 |
| ever | Found | 4800 | 77600 |
| snail | Not Found | 4500 | 74200 |
| better | Not Found | 3900 | 80700 |
| apple | Found | 5700 | 49700 |
| door | Found | 3300 | 7300 |
| foolish | Found | 4000 | 52000 |
### Q4
A proper binary tree contains N nodes. What is the number of leaf nodes in the tree? What is the
number of non-leaf nodes in the tree?
```
Leaf nodes = N/2+1 (N must be an odd number, so take the integer of N/2.)
Non-leaf nodes = N/2
```
### Q5
A complete binary tree has a depth of 8. What is the total number of nodes in the tree? Give the
relationship of the depth and the total number of nodes of a complete binary tree in a mathematic
expression.
```
Total nodes = 2^(8+1) 1 = 511
```
### Q6a
Draw the array of the binary tree if it is implemented in an
array.
```
[Q]
/ \
[B] [U]
\ / \
[G] [R][W]
/ \
[E] [J]
\ / \
[F] [I] [P]
/
[H]
```
```
0:Q 1:B 2:U 4:G 5:R 6:W 9:E 10:J 20:F 21:I 22:P 43:H
```
### Q6(b)
(b)List the node sequence by
(i) pre-order traversal
```
Q B G E F J I H P U R W
```
(ii) in-order traversal
```
B E F G H I J P Q R U W
```
(iii) post-order traversal
```
F E H I P J G B R W U Q
```
### Q7
Follow the algorithm outlined in the lecture notes, depict the Binary Search Trees created by inserting the items below from left to right. Perform an in-order traversal to check if the nodes are visited in ascending order.
(a) M J W S G L K A B P Z X Y R T
```
M
/ \
/ \
/ \
/ \
J W
/ \ / \
G L / \
/ / / \
A K S Z
\ / \ /
B / \ X
P T \
\ Y
R
```
(b) P W J Y B L S G K M A Z X T R
```
P
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ / \
/ \ / \
B L / \
/ \ / \ S Y
A G / \ / \ / \
K M / \ / \
R T X Z
```
(c) P W J Y B L S G K M A R
```
P
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ S Y
/ \ /
B L R
/ \ / \
A G / \
K M
```
(d) P W J Y B L S G K M A
```
P
/ \
/ \
/ \
/ \
/ \
J W
/ \ / \
/ \ S Y
/ \
B L
/ \ / \
A G / \
K M
```
(e) A B C D E F G H I J K L
```
A
\
B
\
C
\
D
\
E
\
F
\
G
\
H
\
I
\
J
\
K
\
L
```
(f) L K J I H G F E D C B A
```
L
/
K
/
J
/
I
/
H
/
G
/
F
/
E
/
D
/
C
/
B
/
A
```
### Q8
Outline an algorithm of searching an item in a Binary Search Tree.
```
BinaryNode search (BinaryNode t, key x)
begin
if t is null
return null;
if (x is less than t.data.key)
return search(t.left, x);
else if (x is greater than t.data.key)
return search(t.right, x);
else
return t;
end
```
### Q10
Give the postfix and prefix expressions as well as the expression tree.
((A + B) * C) / (D + E) * F
```
[*]
/ \
[/] [F]
/ \
/ \
/ \
[*] [+]
/ \ / \
[+] [C] [D] [E]
/ \
/ \
[A] [B]
pre-order traversal on the expression tree to yields the prefix expression
Prefix expression: * / * + A B C + D E F
```

View File

@@ -0,0 +1,89 @@
public class StringBst {
private StringBstNode root;
public StringBst() {
root = null;
}
public void addNode(String data) {
StringBstNode p = root, prev = null;
if (root == null) {
root = new StringBstNode(data);
return;
}
while (p != null) {
prev = p;
if (data.compareTo(p.getData()) < 0) {
p = p.getLeft();
} else {
p = p.getRight();
}
}
if (data.compareTo(prev.getData()) < 0) {
prev.setLeft(new StringBstNode(data));
} else {
prev.setRight(new StringBstNode(data));
}
}
public String search(String data) {
StringBstNode p = root;
if (root == null) {
return null;
}
while (p!=null) {
if (data.compareTo(p.getData()) < 0) {
p = p.getLeft();
} else if(data.compareTo(p.getData()) > 0){
p = p.getRight();
}
else{
return p.getData();
}
}
return null;
}
public void preorder() {
preorder(root);
}
public void preorder(StringBstNode v) {
System.out.print(v.getData() + " ");
if (v.getLeft() != null) {
preorder(v.getLeft());
}
if (v.getRight() != null) {
preorder(v.getRight());
}
}
public void inorder() {
inorder(root);
}
public void inorder(StringBstNode v) {
if (v.getLeft() != null) {
inorder(v.getLeft());
}
System.out.print(v.getData() + " ");
if (v.getRight() != null) {
inorder(v.getRight());
}
}
public void postorder() {
postorder(root);
}
public void postorder(StringBstNode v) {
if (v.getLeft() != null) {
postorder(v.getLeft());
}
if (v.getRight() != null) {
postorder(v.getRight());
}
System.out.print(v.getData() + " ");
}
}

View File

@@ -0,0 +1,32 @@
public class StringBstNode {
private String data;
private StringBstNode left;
private StringBstNode right;
public StringBstNode(String data) {
this.data = data;
this.left = null;
this.right = null;
}
public String getData() {
return data;
}
public StringBstNode getLeft() {
return left;
}
public StringBstNode getRight() {
return right;
}
public void setLeft(StringBstNode p) {
left = p;
}
public void setRight(StringBstNode p){
right =p;
}
}

View File

@@ -0,0 +1,853 @@
water
button
door
able
circle
near
comfort
sock
open
only
road
addition
plough
science
level
expansion
ear
education
insurance
shake
fixed
bone
card
laugh
winter
burst
answer
physical
sense
get
clear
thumb
island
eye
ornament
gold
again
old
point
purpose
plate
distance
drop
daughter
VTC
range
silk
rain
brown
interest
business
skin
condition
danger
paste
boy
adjustment
polish
time
net
jump
fight
stomach
talk
white
animal
neck
no
garden
list
star
drink
chest
tin
feeble
direction
and
land
warm
than
digestion
manager
match
mixed
moon
quiet
tray
jelly
transport
chin
wait
hand
opinion
use
join
cook
potato
cloud
heart
debt
stop
snake
complex
fowl
mind
month
arch
growth
care
plane
argument
about
say
because
ship
colour
responsible
elastic
flag
error
front
hear
wax
ray
coal
unit
suggestion
well
news
trousers
surprise
prison
bread
beautiful
death
wound
harmony
mine
river
opposite
off
this
ant
history
cough
watch
observation
move
not
balance
cry
relation
pull
if
clean
cover
breath
weather
comb
that
trouble
smash
root
voice
sail
disease
important
cup
look
belief
give
hate
over
forward
basket
soap
before
oven
coat
have
exchange
berry
branch
brick
umbrella
political
crack
in
goat
he
bad
dust
far
night
word
structure
mist
the
violent
stretch
keep
pot
rhythm
across
necessary
pen
other
sharp
middle
cushion
brush
cloth
reaction
chief
military
late
electric
brass
ball
married
roll
dress
under
plant
awake
camera
need
quick
knee
great
example
wing
property
seat
shoe
smoke
equal
fold
boat
sudden
wrong
start
fat
shelf
servant
past
safe
tail
cake
to
low
simple
rod
attraction
stick
trick
natural
why
rub
church
bell
you
secret
wave
humour
loud
step
disgust
canvas
idea
insect
mother
boiling
by
mark
fish
west
wine
dog
butter
where
gun
ring
bee
wool
end
basin
stem
verse
company
nail
cotton
account
who
bulb
slow
taste
note
engine
amusement
spring
face
conscious
female
go
slope
play
wood
north
drain
automatic
finger
roof
school
FALSE
loss
sound
form
new
rate
father
cord
place
pig
behaviour
material
peace
committee
board
attack
shade
see
sex
needle
but
table
hour
year
porter
salt
with
oil
flight
bed
seed
money
sweet
rule
fact
black
against
for
baby
loose
quite
support
learning
edge
tax
writing
waste
decision
damage
make
down
sand
man
sticky
wall
then
love
will
doubt
pipe
shame
little
grip
still
tree
body
pocket
left
let
morning
earth
through
pin
copper
picture
leather
representative
field
birth
egg
limit
print
thin
fiction
control
walk
discussion
payment
sleep
song
cheap
knowledge
sea
public
present
as
steam
angry
army
fire
milk
discovery
after
future
sneeze
strong
trade
question
fork
vessel
room
rough
horse
reward
slip
work
deep
nation
linen
from
rice
east
grey
while
order
blow
south
so
process
week
dry
sister
price
tendency
back
blood
jewel
I
stiff
chemical
substance
seem
group
whistle
hair
experience
bird
push
yesterday
knife
how
may
wide
general
thick
secretary
foot
certain
hammer
band
expert
hanging
bottle
attention
motion
prose
development
stage
head
cheese
effect
brother
wind
credit
language
shock
at
produce
cow
out
up
sad
bit
high
nose
complete
law
almost
music
metal
arm
frame
round
degree
sign
apple
bridge
twist
steel
self
line
noise
pencil
knot
be
small
send
snow
ice
copy
detail
bitter
chance
space
muscle
dear
put
special
top
poor
soup
industry
rest
stamp
part
destruction
a
bucket
tight
dark
bent
hospital
rail
hollow
stitch
office
competition
house
pleasure
religion
change
soft
punishment
ready
heat
page
turn
chain
train
spoon
design
tomorrow
advertisement
probable
fear
act
summer
toe
increase
yes
full
throat
much
when
woman
judge
memory
floor
different
cork
tired
liquid
kick
sugar
shut
impulse
scale
view
foolish
air
like
whip
pump
tooth
existence
name
brake
key
flower
letter
cat
tall
hearing
lead
strange
smooth
silver
cruel
nut
town
selection
test
first
base
wire
boot
tongue
enough
girl
acid
authority
spade
grain
light
broken
regret
fly
young
help
every
normal
fall
parallel
orange
leg
curve
lock
please
harbour
measure
mass
building
angle
smell
early
powder
blade
profit
street
crime
cold
paper
cart
government
record
sort
force
driving
of
lift
pain
bag
take
now
such
or
hard
meal
long
weight
flame
regular
red
common
parcel
collar
clock
meat
some
blue
fertile
cause
statement
market
scissors
thought
color
theory
value
sky
dependent
poison
comparison
green
window
among
division
station
store
wise
feather
right
art
hole
system
size
map
screw
kiss
ink
run
carriage
invention
desire
current
library
event
chalk
ticket
agreement
horn
reading
between
hook
brain
flat
protest
monkey
come
even
true
short
organization
number
power
male
operation
journey
distribution
reason
minute
story
sponge
worm
thread
apparatus
stone
frequent
friend
wet
family
sun
bath
grass
lip
iron
wash
living
machine
hat
kind
any
good
side
war
mountain
glass
quality
separate
instrument
country
together
curtain
free
approval
day
way
request
society
attempt
waiting
receipt
cup
medical
swim
all
yellow
offer
glove
person
shirt
delicate
square
feeling
teaching
narrow
drawer
paint
position
dead
meeting
solid
same
healthy
serious
last
very
owner
there
burn
private
food
touch
straight
book
son
ill
kettle
skirt
on
fruit
stocking
box
thunder
happy
guide
leaf
respect
nerve
smile
second
bright
possible
do
rat
mouth
bite
sheep
thing
farm
connection
hope
till
crush
dirty
amount
wheel
ever