├── L01-OOP ├── Q2 │ ├── text4.txt │ ├── text2.txt │ ├── text3.txt │ ├── text1.txt │ └── TextFileReader.java ├── L1 - Prog Fundamental .pdf ├── Q4 │ ├── Test.java │ ├── Transaction.java │ └── Account.java ├── Q3 │ ├── Test.java │ └── Account.java └── Q1 │ ├── name_matricNum.txt │ └── ReadMyLetter_matricNum.java ├── L07-Queue ├── L7 Queue.pdf ├── Q2 │ └── Palindrome.java ├── Q1 │ ├── MyQueue.java │ └── TestMyQueue.java └── Q3 │ └── Trading.java ├── L06-Stack ├── L6 - Stack.pdf ├── Q5 │ ├── Disk.java │ └── TowerOfHanoi.java ├── Q3 │ └── FindSum.java ├── Q1 │ ├── TestMyStack.java │ └── MyStack.java ├── Q4 │ └── Palindrome.java └── Q2 │ └── TestIntMyStack.java ├── L08-Graph ├── L8 - Graph.pdf ├── Graph.java ├── Edge.java ├── Vertex.java ├── TestWeightedGraph.java ├── TestGraph.java └── WeightedGraph.java ├── L11-Tree ├── Lab 11-BST.pdf ├── TreeNode.java ├── TestBST.java └── BST.java ├── L02-Generics ├── L2 - Generics.pdf ├── Q2 │ ├── MyGeneric.java │ └── Test.java ├── Q5 │ ├── Circle.java │ └── FindMax.java ├── Q1 │ ├── Test.java │ └── StorePair.java ├── Q4 │ └── MinMax.java ├── Q3 │ └── CompareMax.java └── Q6 │ └── MinMaxTwoDArray.java ├── L09-Recursion ├── L9 - Recursion.pdf ├── Q3 │ └── Exponent.java ├── Q1 │ └── SubstituteAI.java └── Q2 │ └── Permutation.java ├── L04-Linked List ├── L4 - LinkedList.pdf ├── Node.java ├── TestLinkedList2.java ├── TestLinkedList.java └── MyLinkedList.java ├── Lab Test ├── 1-OOP │ └── Set A │ │ ├── Lab test 1a.pdf │ │ ├── Item.java │ │ ├── Person.java │ │ ├── FashionStore.java │ │ ├── FoodStore.java │ │ ├── ShopLot.java │ │ └── ShoppingMall.java ├── 2-Stack │ └── Set A │ │ ├── Lab Test 2a.pdf │ │ ├── Person.java │ │ ├── Stack.java │ │ └── Main.java ├── 3-Recursion │ ├── Set A │ │ ├── Lab Test 3a.pdf │ │ ├── Q2.java │ │ └── Q3.java │ └── Set B │ │ └── Lab Test 3b.pdf └── README.md ├── L03-ADTs and Bags ├── L3 - ADTs and Bags.pdf ├── ArrayBagDemo.java ├── BagInterface.java └── ArrayBag.java ├── L10-Searching and Sorting ├── L10 - Search-Sort.pdf ├── L10Q4.java ├── L10Q2.java ├── L10Q1.java └── Test.java ├── L05-Doubly Linked List ├── L5 - DoublyLinkedList.pdf ├── Q2 │ ├── SNode.java │ ├── SinglyLinkedList.java │ └── StudentManagementSystem.java ├── Q1 │ └── SList │ │ ├── SNode.java │ │ ├── TestSList.java │ │ └── SList.java └── Q3 │ ├── DNode.java │ ├── TestDoublyLinkedList.java │ └── DoublyLinkedList.java └── README.md /L01-OOP/Q2/text4.txt: -------------------------------------------------------------------------------- 1 | abc123def456ghi789jkl -------------------------------------------------------------------------------- /L01-OOP/Q2/text2.txt: -------------------------------------------------------------------------------- 1 | 15, 2, 9, 78, 33, 61 2 | 198, 523, 91, 42, 13, 77 3 | 34, 45 -------------------------------------------------------------------------------- /L01-OOP/Q2/text3.txt: -------------------------------------------------------------------------------- 1 | 4.33; 2.51; 6.11; 2.33; 6.31 2 | 1.95; 3.67; 2.22 3 | 6.84; 5.04; 9.56; 0.92 -------------------------------------------------------------------------------- /L07-Queue/L7 Queue.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L07-Queue/L7 Queue.pdf -------------------------------------------------------------------------------- /L06-Stack/L6 - Stack.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L06-Stack/L6 - Stack.pdf -------------------------------------------------------------------------------- /L08-Graph/L8 - Graph.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L08-Graph/L8 - Graph.pdf -------------------------------------------------------------------------------- /L11-Tree/Lab 11-BST.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L11-Tree/Lab 11-BST.pdf -------------------------------------------------------------------------------- /L02-Generics/L2 - Generics.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L02-Generics/L2 - Generics.pdf -------------------------------------------------------------------------------- /L09-Recursion/L9 - Recursion.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L09-Recursion/L9 - Recursion.pdf -------------------------------------------------------------------------------- /L01-OOP/L1 - Prog Fundamental .pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L01-OOP/L1 - Prog Fundamental .pdf -------------------------------------------------------------------------------- /L04-Linked List/L4 - LinkedList.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L04-Linked List/L4 - LinkedList.pdf -------------------------------------------------------------------------------- /Lab Test/1-OOP/Set A/Lab test 1a.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/Lab Test/1-OOP/Set A/Lab test 1a.pdf -------------------------------------------------------------------------------- /Lab Test/2-Stack/Set A/Lab Test 2a.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/Lab Test/2-Stack/Set A/Lab Test 2a.pdf -------------------------------------------------------------------------------- /L03-ADTs and Bags/L3 - ADTs and Bags.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L03-ADTs and Bags/L3 - ADTs and Bags.pdf -------------------------------------------------------------------------------- /Lab Test/3-Recursion/Set A/Lab Test 3a.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/Lab Test/3-Recursion/Set A/Lab Test 3a.pdf -------------------------------------------------------------------------------- /Lab Test/3-Recursion/Set B/Lab Test 3b.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/Lab Test/3-Recursion/Set B/Lab Test 3b.pdf -------------------------------------------------------------------------------- /L10-Searching and Sorting/L10 - Search-Sort.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L10-Searching and Sorting/L10 - Search-Sort.pdf -------------------------------------------------------------------------------- /L05-Doubly Linked List/L5 - DoublyLinkedList.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DragonKnightMax/WIA1002/HEAD/L05-Doubly Linked List/L5 - DoublyLinkedList.pdf -------------------------------------------------------------------------------- /Lab Test/README.md: -------------------------------------------------------------------------------- 1 | # WIA1002-2021 Lab Test 2 | 3 | ### Question file 4 | All the questions file extensions are `*.pdf` 5 | 6 | - Set A `*a.pdf` 7 | - Set B `*b.pdf` 8 | -------------------------------------------------------------------------------- /L01-OOP/Q2/text1.txt: -------------------------------------------------------------------------------- 1 | S,U,C,E,S,S 2 | A,c,c,o,m,p,l,i,s,h,m,e,n,t 3 | B,r,i,l,l,i,a,n,t 4 | C,r,e,a,t,i,v,e 5 | D,e,t,e,r,m,i,n,a,t,i,o,n 6 | E,n,c,o,u,r,a,g,i,n,g 7 | F,o,c,u,s -------------------------------------------------------------------------------- /L04-Linked List/Node.java: -------------------------------------------------------------------------------- 1 | public class Node { 2 | E element; 3 | Node next; 4 | 5 | public Node() { 6 | } 7 | 8 | public Node(E element) { 9 | this.element = element; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /L11-Tree/TreeNode.java: -------------------------------------------------------------------------------- 1 | public class TreeNode> { 2 | E element; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | public TreeNode(E e) { 7 | this.element = e; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q2/SNode.java: -------------------------------------------------------------------------------- 1 | public class SNode { 2 | E element; 3 | SNode next; 4 | 5 | public SNode() { 6 | } 7 | 8 | public SNode(E element) { 9 | this.element = element; 10 | this.next = null; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q1/SList/SNode.java: -------------------------------------------------------------------------------- 1 | package SList; 2 | 3 | public class SNode { 4 | E element; 5 | SNode next; 6 | 7 | public SNode() { 8 | } 9 | 10 | public SNode(E e) { 11 | this.element = e; 12 | this.next = null; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /L02-Generics/Q2/MyGeneric.java: -------------------------------------------------------------------------------- 1 | public class MyGeneric { 2 | private T e; 3 | 4 | public MyGeneric() { 5 | } 6 | 7 | public MyGeneric(T e) { 8 | this.e = e; 9 | } 10 | 11 | public T getE() { 12 | return e; 13 | } 14 | 15 | public void setE(T e) { 16 | this.e = e; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /L02-Generics/Q2/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | public static void main(String[] args) { 3 | MyGeneric strObj = new MyGeneric<>(); 4 | strObj.setE("Hello"); 5 | System.out.println(strObj.getE()); 6 | 7 | MyGeneric intObj = new MyGeneric<>(); 8 | intObj.setE(5); 9 | System.out.println(intObj.getE()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q3/DNode.java: -------------------------------------------------------------------------------- 1 | public class DNode { 2 | E element; 3 | DNode next; 4 | DNode prev; 5 | 6 | public DNode(E element) { 7 | this(element, null, null); 8 | } 9 | 10 | public DNode(E element, DNode next, DNode prev) { 11 | this.element = element; 12 | this.next = next; 13 | this.prev = prev; 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /L06-Stack/Q5/Disk.java: -------------------------------------------------------------------------------- 1 | public class Disk { 2 | private int size; 3 | 4 | public Disk(int size) { 5 | this.size = size; 6 | } 7 | 8 | public int getSize() { 9 | return size; 10 | } 11 | 12 | public void setSize(int size) { 13 | this.size = size; 14 | } 15 | 16 | @Override 17 | public String toString() { 18 | return "" + size; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /L08-Graph/Graph.java: -------------------------------------------------------------------------------- 1 | package Lab.L8; 2 | 3 | public class Graph> extends WeightedGraph { 4 | 5 | public boolean addEdge(T source, T destination) { 6 | return super.addEdge(source, destination, 1); 7 | } 8 | 9 | public boolean addUndirectedEdge(T source, T destination) { 10 | return addEdge(source, destination) && addEdge(destination, source); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /L01-OOP/Q4/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | public static void main(String[] args) { 3 | Account account = new Account("George", 1122, 1000); 4 | account.setAnnualInterestRate(1.5); 5 | account.deposit(30); 6 | account.deposit(40); 7 | account.deposit(50); 8 | account.withdraw(5); 9 | account.withdraw(4); 10 | account.withdraw(2); 11 | System.out.println(account.toString()); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /L06-Stack/Q3/FindSum.java: -------------------------------------------------------------------------------- 1 | import java.util.Stack; 2 | 3 | public class FindSum { 4 | 5 | public static void main(String[] args) { 6 | Stack stack = new Stack<>(); 7 | for (int i = 1; i <= 20; i++) { 8 | stack.push(i); 9 | } 10 | 11 | int sum = 0; 12 | while (!stack.isEmpty()) { 13 | sum += stack.pop(); 14 | } 15 | 16 | System.out.println("Sum of every element in stack is " + sum); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /L09-Recursion/Q3/Exponent.java: -------------------------------------------------------------------------------- 1 | public class Exponent { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(exponent(10, 3)); 5 | System.out.println(exponent(2, 8)); 6 | System.out.println(exponent(5, 3)); 7 | } 8 | 9 | public static long exponent(int x, int m) { 10 | // Base case 11 | if (m == 0) { 12 | return 1; 13 | } 14 | // Recursive case 15 | return (x * exponent(x, --m)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /L01-OOP/Q3/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | public static void main(String[] args) { 3 | Account account = new Account(1122, 20000); 4 | account.setAnnualInterestRate(4.5); 5 | account.withdraw(2500); 6 | account.deposit(3000); 7 | 8 | System.out.println("Account Balance\t\t: " + account.getBalance()); 9 | System.out.println("Monthly Interest\t: " + account.getMonthlyInterest()); 10 | System.out.println("Date created\t\t: " + account.getDateCreated()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /L08-Graph/Edge.java: -------------------------------------------------------------------------------- 1 | package Lab.L8; 2 | 3 | public class Edge, N extends Comparable> { 4 | Vertex toVertex; 5 | N weight; 6 | Edge nextEdge; 7 | 8 | public Edge() { 9 | this.toVertex = null; 10 | this.weight = null; 11 | this.nextEdge = null; 12 | } 13 | 14 | public Edge(Vertex toVertex, N weight, Edge nextEdge) { 15 | this.toVertex = toVertex; 16 | this.weight = weight; 17 | this.nextEdge = nextEdge; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /L08-Graph/Vertex.java: -------------------------------------------------------------------------------- 1 | package Lab.L8; 2 | 3 | public class Vertex, N extends Comparable> { 4 | T vertexInfo; 5 | int indeg; 6 | int outdeg; 7 | Vertex nextVertex; 8 | Edge firstEdge; 9 | 10 | public Vertex() { 11 | this(null, null); 12 | } 13 | 14 | public Vertex(T vertexInfo, Vertex nextVertex) { 15 | this.vertexInfo = vertexInfo; 16 | this.indeg = 0; 17 | this.outdeg = 0; 18 | this.nextVertex = nextVertex; 19 | this.firstEdge = null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /L02-Generics/Q5/Circle.java: -------------------------------------------------------------------------------- 1 | package Lab.L2.Q5; 2 | 3 | public class Circle implements Comparable { 4 | private double radius; 5 | 6 | public Circle(double radius) { 7 | this.radius = radius; 8 | } 9 | 10 | public double getRadius() { 11 | return radius; 12 | } 13 | 14 | public void setRadius(double radius) { 15 | this.radius = radius; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "Radius of circle: " + radius; 21 | } 22 | 23 | @Override 24 | public int compareTo(Circle o) { 25 | return Double.compare(radius, o.getRadius()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /L10-Searching and Sorting/L10Q4.java: -------------------------------------------------------------------------------- 1 | public class L10Q4 { 2 | 3 | public static void main(String[] args) { 4 | int[] arr = {10, 34, 2, 56, 7, 67, 88, 42}; 5 | insertionSort(arr); 6 | 7 | for (int num : arr) { 8 | System.out.print(num + " "); 9 | } 10 | } 11 | 12 | public static void insertionSort(int[] arr) { 13 | for (int i = 1; i < arr.length; i++) { 14 | int current = arr[i]; 15 | int k; 16 | for (k = i - 1; (k >= 0) && (arr[k] > current); k--) { 17 | arr[k + 1] = arr[k]; 18 | } 19 | arr[k + 1] = current; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /L04-Linked List/TestLinkedList2.java: -------------------------------------------------------------------------------- 1 | public class TestLinkedList2 { 2 | 3 | public static void main(String[] args) { 4 | MyLinkedList myLinkedList = new MyLinkedList<>(); 5 | 6 | // append the following: a, b,c, d, e 7 | myLinkedList.addLast('a'); 8 | myLinkedList.addLast('b'); 9 | myLinkedList.addLast('c'); 10 | myLinkedList.addLast('d'); 11 | myLinkedList.addLast('e'); 12 | 13 | // print all the elements in the list 14 | System.out.print("All the elements in the list: "); 15 | myLinkedList.print(); 16 | 17 | System.out.println("Middle value: " + myLinkedList.getMiddleValue()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /L10-Searching and Sorting/L10Q2.java: -------------------------------------------------------------------------------- 1 | public class L10Q2 { 2 | 3 | public void selectionSortLargest(int[] arr) { 4 | for (int i = 0; i < arr.length; i++) { 5 | int currentLargestIndex = i; 6 | int currentLargest = arr[i]; 7 | 8 | for (int j = i + 1; j < arr.length; j++) { 9 | if (arr[j] > currentLargest) { 10 | currentLargestIndex = j; 11 | currentLargest = arr[j]; 12 | } 13 | } 14 | 15 | if (currentLargestIndex != i) { 16 | arr[currentLargestIndex] = arr[i]; 17 | arr[i] = currentLargest; 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /L10-Searching and Sorting/L10Q1.java: -------------------------------------------------------------------------------- 1 | public class L10Q1 { 2 | 3 | public void selectionSortSmallest(int[] arr) { 4 | for (int i = 0; i < arr.length; i++) { 5 | int currentSmallestIndex = i; 6 | int currentSmallest = arr[i]; 7 | 8 | for (int j = i + 1; j < arr.length; j++) { 9 | if (arr[j] < currentSmallest) { 10 | currentSmallestIndex = j; 11 | currentSmallest = arr[j]; 12 | } 13 | } 14 | 15 | if (currentSmallestIndex != i) { 16 | arr[currentSmallestIndex] = arr[i]; 17 | arr[i] = currentSmallest; 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /L09-Recursion/Q1/SubstituteAI.java: -------------------------------------------------------------------------------- 1 | public class SubstituteAI { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(substituteAI("flabbergasted")); 5 | System.out.println(substituteAI("Astronaut")); 6 | } 7 | 8 | public static String substituteAI(String word) { 9 | // base case: string length == 0 10 | if (word.length() < 1) { 11 | return ""; 12 | } 13 | // Recursive case 14 | char letter = word.charAt(0); 15 | String remaining = word.substring(1); // slice the string 16 | if (letter == 'a') { 17 | return "i" + substituteAI(remaining); 18 | } 19 | return letter + substituteAI(remaining); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Lab Test/1-OOP/Set A/Item.java: -------------------------------------------------------------------------------- 1 | public class Item { 2 | private String name; 3 | private int price; 4 | 5 | public Item(String name, int price) { 6 | this.name = name; 7 | this.price = price; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public int getPrice() { 15 | return price; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public void setPrice(int price) { 23 | this.price = price; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return "Item{" + 29 | "item='" + name + '\'' + 30 | ", price=" + price + 31 | '}'; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /L02-Generics/Q5/FindMax.java: -------------------------------------------------------------------------------- 1 | package Lab.L2.Q5; 2 | 3 | public class FindMax { 4 | 5 | public static void main(String[] args) { 6 | Integer[] intArr = {1, 2, 3}; 7 | String[] strArr = {"red", "green", "blue"}; 8 | Circle[] circles = {new Circle(3), new Circle(2.9), new Circle(5.9)}; 9 | 10 | System.out.println(max(intArr)); 11 | System.out.println(max(strArr)); 12 | System.out.println(max(circles)); 13 | } 14 | 15 | public static > E max(E[] list) { 16 | E maximum = list[0]; 17 | for (int i = 1; i < list.length; i++) { 18 | if (list[i].compareTo(maximum) > 0) { 19 | maximum = list[i]; 20 | } 21 | } 22 | return maximum; 23 | } 24 | } -------------------------------------------------------------------------------- /L02-Generics/Q1/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | public static void main(String[] args) { 3 | StorePair a = new StorePair<>(6, 4); 4 | StorePair b = new StorePair<>(2, 2); 5 | StorePair c = new StorePair<>(6, 3); 6 | 7 | if (a.compareTo(b) > 0 && a.compareTo(c) > 0) { 8 | System.out.println(a); 9 | } else if (b.compareTo(a) > 0 && b.compareTo(c) > 0) { 10 | System.out.println(b); 11 | } else if (c.compareTo(a) > 0 && c.compareTo(b) > 0) { 12 | System.out.println(c); 13 | } 14 | 15 | System.out.println("a == b : " + a.equals(b)); 16 | System.out.println("b == c : " + b.equals(c)); 17 | System.out.println("a == c : " + a.equals(c)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /L10-Searching and Sorting/Test.java: -------------------------------------------------------------------------------- 1 | public class Test { 2 | 3 | public static void main(String[] args) { 4 | int[] arr = {45, 7, 2, 8, 19, 3}; 5 | 6 | // Q1 7 | L10Q1 result1 = new L10Q1(); 8 | result1.selectionSortSmallest(arr); 9 | 10 | System.out.println("selectionSortSmallest(int[] arr)"); 11 | for (int num : arr) { 12 | System.out.print(num + " "); 13 | } 14 | System.out.println(); 15 | 16 | // Q2 17 | L10Q2 result2 = new L10Q2(); 18 | result2.selectionSortLargest(arr); 19 | 20 | System.out.println("selectionSortLargest(int[] arr)"); 21 | for (int num : arr) { 22 | System.out.print(num + " "); 23 | } 24 | System.out.println(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /L06-Stack/Q1/TestMyStack.java: -------------------------------------------------------------------------------- 1 | public class TestMyStack { 2 | 3 | public static void main(String[] args) { 4 | 5 | MyStack stack = new MyStack<>(); 6 | 7 | stack.push('a'); 8 | stack.push('b'); 9 | stack.push('c'); 10 | 11 | System.out.println(stack); 12 | 13 | System.out.println("element 'b' is in the stack: " + stack.search('b')); 14 | 15 | System.out.println("element 'k' is in the stack: " + stack.search('k')); 16 | 17 | 18 | MyStack intStack = new MyStack<>(); 19 | 20 | intStack.push(1); 21 | intStack.push(2); 22 | intStack.push(3); 23 | 24 | System.out.println(intStack); 25 | 26 | System.out.println("Element '6' is in the stack: " + intStack.search(6)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q3/TestDoublyLinkedList.java: -------------------------------------------------------------------------------- 1 | public class TestDoublyLinkedList { 2 | 3 | public static void main(String[] args) { 4 | DoublyLinkedList doublyLinkedList = new DoublyLinkedList<>(); 5 | 6 | doublyLinkedList.addFirst(1); 7 | doublyLinkedList.addLast(10); 8 | doublyLinkedList.add(2, 2); 9 | doublyLinkedList.addLast(100); 10 | doublyLinkedList.remove(3); 11 | 12 | System.out.println(); 13 | doublyLinkedList.traverseForward(); 14 | doublyLinkedList.traverseBackward(); 15 | 16 | System.out.println("size of current Doubly Linked List: " + doublyLinkedList.getSize()); 17 | 18 | doublyLinkedList.clear(); 19 | 20 | System.out.println("\nsize of current Doubly Linked List: " + doublyLinkedList.getSize()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /L07-Queue/Q2/Palindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Palindrome { 4 | 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | System.out.print("Enter a string: "); 8 | String before = scanner.nextLine(); 9 | 10 | MyQueue queue = new MyQueue<>(); 11 | for (int i = before.length() - 1; i >= 0; i--) { 12 | queue.enqueue(before.charAt(i)); 13 | } 14 | 15 | String after = ""; 16 | while (!queue.isEmpty()) { 17 | after += queue.dequeue().toString(); 18 | } 19 | 20 | if (before.equalsIgnoreCase(after)) { 21 | System.out.println("Palindrome"); 22 | } 23 | else { 24 | System.out.println("Not a palindrome"); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /L02-Generics/Q4/MinMax.java: -------------------------------------------------------------------------------- 1 | public class MinMax { 2 | 3 | public static void main(String[] args) { 4 | Integer[] intArray = {5, 3, 7, 1, 4, 9, 8, 2}; 5 | String[] strArray = {"red", "blue", "orange", "tan"}; 6 | 7 | System.out.println(minmax(intArray)); 8 | System.out.println(minmax(strArray)); 9 | } 10 | 11 | public static > String minmax(T[] arr) { 12 | T min = arr[0]; 13 | T max = arr[0]; 14 | 15 | for (int i = 1; i < arr.length; i++) { 16 | T item = arr[i]; 17 | 18 | if (item.compareTo(max) > 0) { 19 | max = item; 20 | } 21 | if (item.compareTo(min) < 0) { 22 | min = item; 23 | } 24 | } 25 | return String.format("Min = %s Max = %s", min, max); 26 | } 27 | } -------------------------------------------------------------------------------- /L06-Stack/Q4/Palindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Stack; 3 | 4 | public class Palindrome { 5 | 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | System.out.print("Enter a string: "); 9 | String before = scanner.nextLine(); 10 | 11 | Stack stack = new Stack<>(); 12 | for (int i = 0; i < before.length(); i++) { 13 | stack.push(before.charAt(i)); 14 | } 15 | 16 | String after = ""; 17 | while (!stack.isEmpty()) { 18 | after += stack.pop().toString(); 19 | } 20 | 21 | if (before.equalsIgnoreCase(after)) { 22 | System.out.println("Palindrome!"); 23 | } 24 | else { 25 | System.out.println("Not a palindrome"); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /L09-Recursion/Q2/Permutation.java: -------------------------------------------------------------------------------- 1 | public class Permutation { 2 | 3 | public static void main(String[] args) { 4 | permuteString("", "DOG"); 5 | } 6 | 7 | public static void permuteString(String beginningString, String endingString) { 8 | // See the process 9 | //System.out.println(beginningString + ", " + endingString); 10 | 11 | // Base case 12 | if (endingString.length() <= 1) { 13 | System.out.println(beginningString + endingString); 14 | } 15 | // Recursive case 16 | else { 17 | for (int i = 0; i < endingString.length(); i++) { 18 | String newString = endingString.substring(0, i) + endingString.substring(i + 1); 19 | permuteString(beginningString + endingString.charAt(i), newString); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /L06-Stack/Q1/MyStack.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class MyStack { 4 | private ArrayList list; 5 | 6 | public MyStack() { 7 | list = new ArrayList<>(); 8 | } 9 | 10 | public void push(E o) { 11 | list.add(o); 12 | } 13 | 14 | public E pop() { 15 | return list.remove(this.getSize() - 1); 16 | 17 | } 18 | 19 | public E peek() { 20 | return list.get(0); 21 | } 22 | 23 | public int getSize() { 24 | return list.size(); 25 | } 26 | 27 | public boolean isEmpty() { 28 | return list.isEmpty(); 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "MyStack{" + 34 | "list=" + list.toString() + 35 | '}'; 36 | } 37 | 38 | public boolean search(E o) { 39 | return list.contains(o); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Lab Test/1-OOP/Set A/Person.java: -------------------------------------------------------------------------------- 1 | public class Person { 2 | private String name; 3 | private String contactNumber; 4 | 5 | public Person(String name, String contactNumber) { 6 | this.name = name; 7 | this.contactNumber = contactNumber; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public String getContactNumber() { 15 | return contactNumber; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public void setContactNumber(String contactNumber) { 23 | this.contactNumber = contactNumber; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return "Person{" + 29 | "name='" + name + '\'' + 30 | ", contactNo='" + contactNumber + '\'' + 31 | '}'; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /L02-Generics/Q3/CompareMax.java: -------------------------------------------------------------------------------- 1 | public class CompareMax { 2 | 3 | public static void main(String[] args) { 4 | System.out.println(maximum("a", "b", "c")); 5 | System.out.println(maximum("a", "a", "b")); 6 | 7 | System.out.println(maximum(2, 2, 1)); 8 | System.out.println(maximum(2, 1, 2)); 9 | System.out.println(maximum(1, 2, 2)); 10 | System.out.println(maximum(1, 1, 1)); 11 | System.out.println(maximum(1, 2, 3)); 12 | System.out.println(maximum(3, 2, 1)); 13 | System.out.println(maximum(2, 3, 1)); 14 | } 15 | 16 | public static > T maximum(T a, T b, T c) { 17 | if (a.compareTo(b) >= 0 && a.compareTo(c) >= 0) 18 | return a; 19 | else if (b.compareTo(a) >= 0 && b.compareTo(c) >= 0) 20 | return b; 21 | else 22 | return c; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WIA1002 Data Structure 2 | 3 | ## Project Description 4 | 5 | This is my solution for the lab questions of WIA1002 Data Structure, Semester 2, 2020/2021 when I am a First Year student at University of Malaya. 6 | 7 | ## Table of Content 8 | 9 | ### Lab 10 | 11 | - 01-OOP 12 | - 02-Generics 13 | - 03-ADTs and Bags 14 | - 04-Linked List 15 | - 05-Doubly Linked List 16 | - 06-Stack 17 | - 07-Queue 18 | - 08-Graph 19 | - 09-Recursion 20 | - 10-Searching and Sorting 21 | - 11-Binary Search Tree 22 | 23 | ### Lab Test (In Progress...) 24 | 25 | - 01-OOP 26 | - 02-Stack 27 | - 03-Recursion 28 | 29 | ## Contributing 30 | 31 | You can fork this repository as a reference for your learning. Please do not just copy the code directly as you will not learn anything. If you found any errors or bugs🐛 in the code, please feel free to raise any issues. Pull requests are always welcome if you want to contribute to this project. 32 | -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q1/SList/TestSList.java: -------------------------------------------------------------------------------- 1 | package SList; 2 | 3 | public class TestSList { 4 | 5 | public static void main(String[] args) { 6 | SList sList = new SList<>(); 7 | 8 | // Append the following values individually: “Linked list, is, easy.” 9 | sList.appendEnd("Linked list"); 10 | sList.appendEnd("is"); 11 | sList.appendEnd("easy"); 12 | 13 | // Display these values. 14 | sList.display(); 15 | 16 | // Remove the word “Linked list” and display the removed value. 17 | System.out.println("Removed value: " + sList.removeInitial()); 18 | 19 | // Check if ‘difficult’ is in the list. 20 | System.out.println("'difficult' in list: " + sList.contains("difficult")); 21 | 22 | // Clear the list. 23 | sList.clear(); 24 | System.out.println("After clearing list:"); 25 | sList.display(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Lab Test/3-Recursion/Set A/Q2.java: -------------------------------------------------------------------------------- 1 | public class Q2 { 2 | 3 | public static void main(String[] args) { 4 | System.out.println("Mesh Topology"); 5 | display(4); 6 | display(7); 7 | } 8 | 9 | // Helper method to display the total number of connections 10 | public static void display(int switches) { 11 | System.out.printf("There are %d switches in the campus.\n", switches); 12 | System.out.println("The total number of connections required is " + connections(switches)); 13 | } 14 | 15 | // Recursive method to calculate total number of connections required for n switches in campus 16 | public static int connections(int switches) { 17 | // Base case 18 | if (switches <= 1) { 19 | return 0; 20 | } 21 | // Recursive case: c = (n - 1) + (n - 2) + ... + 0 22 | return (switches - 1) + connections(switches - 1); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /L06-Stack/Q2/TestIntMyStack.java: -------------------------------------------------------------------------------- 1 | import Lab.L6.Q1.MyStack; 2 | 3 | import java.util.Scanner; 4 | 5 | // Output of the elements is from 1 to n. 6 | // The output is in th reverse order because stack is a LIFO (last in first out) data structure 7 | 8 | public class TestIntMyStack { 9 | 10 | public static void main(String[] args) { 11 | MyStack intMyStack = new MyStack<>(); 12 | 13 | Scanner input = new Scanner(System.in); 14 | System.out.print("Enter an integer: "); 15 | int n = input.nextInt(); 16 | 17 | for (int i = 1; i <= n; i++) { 18 | intMyStack.push(i); 19 | } 20 | 21 | System.out.println("Size of stack: " + intMyStack.getSize()); 22 | 23 | System.out.println("Content of the stack: "); 24 | while (!intMyStack.isEmpty()) { 25 | System.out.print(intMyStack.pop() + " "); 26 | } 27 | System.out.println(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Lab Test/1-OOP/Set A/FashionStore.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class FashionStore extends ShopLot implements Comparable { 4 | private ArrayList clothes; 5 | 6 | public FashionStore(String shopName, Person contactPerson) { 7 | super(shopName, contactPerson); 8 | this.clothes = new ArrayList<>(); 9 | } 10 | 11 | public void addClothes(String clothesName, int clothesPrice) { 12 | clothes.add(new Item(clothesName, clothesPrice)); 13 | } 14 | 15 | @Override 16 | public int compareTo(FashionStore fashionStore) { 17 | if (super.getNumOfEmployees() > fashionStore.getNumOfEmployees()) 18 | return 1; 19 | else if (super.getNumOfEmployees() < fashionStore.getNumOfEmployees()) 20 | return -1; 21 | return 0; 22 | } 23 | 24 | @Override 25 | public ArrayList getItems() { 26 | return clothes; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /L02-Generics/Q1/StorePair.java: -------------------------------------------------------------------------------- 1 | public class StorePair> implements Comparable> { 2 | private T first, second; 3 | 4 | public StorePair(T first, T second) { 5 | this.first = first; 6 | this.second = second; 7 | } 8 | 9 | public T getFirst() { 10 | return first; 11 | } 12 | 13 | public T getSecond() { 14 | return second; 15 | } 16 | 17 | public void setPair(T first, T second) { 18 | this.first = first; 19 | this.second = second; 20 | } 21 | 22 | @Override 23 | public String toString() { 24 | return "first = " + first + " second = " + second; 25 | } 26 | 27 | @Override 28 | public boolean equals(Object obj) { 29 | if (obj instanceof StorePair) { 30 | return ((StorePair) obj).getFirst().equals(first); 31 | } 32 | return false; 33 | } 34 | 35 | @Override 36 | public int compareTo(StorePair o) { 37 | return first.compareTo(o.getFirst()); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /L01-OOP/Q4/Transaction.java: -------------------------------------------------------------------------------- 1 | import java.util.Date; 2 | 3 | public class Transaction { 4 | private Date date; 5 | private char type; 6 | private final double amount; 7 | private final double balance; 8 | private final String description; 9 | 10 | public Transaction(char type, double amount, double balance, String description) { 11 | this.type = type; 12 | this.amount = amount; 13 | this.balance = balance; 14 | this.description = description; 15 | } 16 | 17 | public Date getDate() { 18 | return date; 19 | } 20 | 21 | public void setDate(Date date) { 22 | this.date = date; 23 | } 24 | 25 | public char getType() { 26 | return type; 27 | } 28 | 29 | public void setType(char type) { 30 | this.type = type; 31 | } 32 | 33 | public double getAmount() { 34 | return amount; 35 | } 36 | 37 | public double getBalance() { 38 | return balance; 39 | } 40 | 41 | public String getDescription() { 42 | return description; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /L07-Queue/Q1/MyQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | 3 | public class MyQueue { 4 | LinkedList list; 5 | 6 | public MyQueue(E[] e) { 7 | list = new LinkedList<>(); 8 | for (int i = 0; i < e.length; i++) { 9 | list.addLast(e[i]); 10 | } 11 | } 12 | 13 | public MyQueue() { 14 | list = new LinkedList<>(); 15 | } 16 | 17 | public void enqueue(E e) { 18 | list.addLast(e); 19 | } 20 | 21 | public E dequeue() { 22 | return list.removeFirst(); 23 | } 24 | 25 | public E getElement(int i) { 26 | return list.get(i); 27 | } 28 | 29 | public E peek() { 30 | return list.getFirst(); 31 | } 32 | 33 | public int getSize() { 34 | return list.size(); 35 | } 36 | 37 | public boolean contains(E e) { 38 | return list.contains(e); 39 | } 40 | 41 | public boolean isEmpty() { 42 | return list.isEmpty(); 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return list.toString(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /L01-OOP/Q1/name_matricNum.txt: -------------------------------------------------------------------------------- 1 | Thursday, 11 March 2020. 2 | 3 | My name is [YOUR_NAME] with matric number, [YOUR_MATRIC_NUMBER]. I am 4 | majoring in Computer Science (Artificial Intelligence). This is my first time taking the 5 | Data Structure subject. At the moment, I am feeling curious about taking this 6 | subject. This is because I have not even heard what data structure actually is. 7 | 8 | I acquired A+ for my previous Programming 1 course. It’s not too bad. So, I 9 | think I can manage to get an A again for this DS subject this term. In order 10 | to do well in the subject, I will study smart and practise programming every day. Wish me luck!!! 11 | 12 | Thursday, 18 June 2021. 13 | 14 | It’s me again. Finally, it’s the end of the term and the DS class has finished! 15 | I think I performed moderately in the class. 16 | I am happy with my performance. 17 | I learn to use data structures in my program to organize the data. 18 | No, my target grade still remains A. 19 | I love lab session because it gives me hands-on learning experience. 20 | I hope there is more hands-on learning session during the course. -------------------------------------------------------------------------------- /L07-Queue/Q1/TestMyQueue.java: -------------------------------------------------------------------------------- 1 | public class TestMyQueue { 2 | 3 | public static void main(String[] args) { 4 | String[] fruits = {"Durian", "Blueberry"}; 5 | MyQueue fruitQ = new MyQueue<>(fruits); 6 | 7 | fruitQ.enqueue("Apple"); 8 | fruitQ.enqueue("Orange"); 9 | fruitQ.enqueue("Grapes"); 10 | fruitQ.enqueue("Cherry"); 11 | 12 | 13 | System.out.println("Content of the queue: " + fruitQ); 14 | 15 | System.out.println("Top item: " + fruitQ.peek()); 16 | 17 | System.out.println("Queue size: " + fruitQ.getSize()); 18 | 19 | System.out.println("Deleted: " + fruitQ.dequeue()); 20 | 21 | System.out.println("Item at index position 2: " + fruitQ.getElement(2)); 22 | 23 | System.out.println("Queue consists of cherry: " + fruitQ.contains("Cherry")); 24 | 25 | System.out.println("Queue consists of durian: " + fruitQ.contains("Durian")); 26 | 27 | System.out.println("Content of queue: "); 28 | while (!fruitQ.isEmpty()) { 29 | System.out.print(fruitQ.dequeue() + " "); 30 | } 31 | System.out.println(); 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /L02-Generics/Q6/MinMaxTwoDArray.java: -------------------------------------------------------------------------------- 1 | package Lab.L2.Q6; 2 | 3 | public class MinMaxTwoDArray { 4 | 5 | public static void main(String[] args) { 6 | Integer[][] numbers = {{4, 5, 6}, {1, 2, 3}}; 7 | System.out.println("Min = " + min(numbers)); 8 | System.out.println("Max = " + max(numbers)); 9 | } 10 | 11 | public static > E min(E[][] list) { 12 | E minimum = list[0][0]; 13 | for (int i = 0; i < list.length; i++) { 14 | for (int j = 0; j < list[i].length; j++) { 15 | if (list[i][j].compareTo(minimum) < 0) { 16 | minimum = list[i][j]; 17 | } 18 | } 19 | } 20 | return minimum; 21 | } 22 | 23 | public static > E max(E[][] list) { 24 | E maximum = list[0][0]; 25 | for (int i = 0; i < list.length; i++) { 26 | for (int j = 0; j < list[i].length; j++) { 27 | if (list[i][j].compareTo(maximum) > 0) { 28 | maximum = list[i][j]; 29 | } 30 | } 31 | } 32 | return maximum; 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Lab Test/1-OOP/Set A/FoodStore.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class FoodStore extends ShopLot implements Comparable { 4 | private ArrayList menu; 5 | 6 | public FoodStore(String shopName, Person contactPerson) { 7 | super(shopName, contactPerson); 8 | this.menu = new ArrayList<>(); 9 | } 10 | 11 | @Override 12 | public int compareTo(FoodStore foodStore) { 13 | if (super.getNumOfEmployees() > foodStore.getNumOfEmployees()) 14 | return 1; 15 | else if (super.getNumOfEmployees() < foodStore.getNumOfEmployees()) 16 | return -1; 17 | return 0; 18 | //return Integer.compare(super.getNumOfEmployees(), foodStore.getNumOfEmployees()); 19 | } 20 | 21 | @Override 22 | public boolean equals(Object obj) { 23 | if (obj instanceof FoodStore) { 24 | return (super.getContactPerson().getName()).equals(((FoodStore) obj).getContactPerson().getName()); 25 | } 26 | return false; 27 | } 28 | 29 | public void addMenu(String foodName, int foodPrice) { 30 | menu.add(new Item(foodName, foodPrice)); 31 | } 32 | 33 | @Override 34 | public ArrayList getItems() { 35 | return menu; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Lab Test/1-OOP/Set A/ShopLot.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class ShopLot { 4 | private String name; 5 | private Person contactPerson; 6 | private final ArrayList employees; 7 | 8 | public ShopLot(String name, Person contactPerson) { 9 | this.name = name; 10 | this.contactPerson = contactPerson; 11 | this.employees = new ArrayList<>(); 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public Person getContactPerson() { 19 | return contactPerson; 20 | } 21 | 22 | public void setName(String name) { 23 | this.name = name; 24 | } 25 | 26 | public void setContactPerson(Person contactPerson) { 27 | this.contactPerson = contactPerson; 28 | } 29 | 30 | public int getNumOfEmployees() { 31 | return employees.size(); 32 | } 33 | 34 | public void addEmployee(String[] employees) { 35 | for (String e : employees) { 36 | this.employees.add(new Person(e, null)); 37 | } 38 | } 39 | 40 | public ArrayList getItems() { 41 | return null; 42 | }; 43 | 44 | @Override 45 | public String toString() { 46 | return "ShopLot{" + 47 | "shopName='" + name + '\'' + 48 | ", contact=" + contactPerson + 49 | ", employees=" + employees + 50 | '}'; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Lab Test/3-Recursion/Set A/Q3.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | 5 | public class Q3 { 6 | static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 7 | 8 | public static void main(String[] args) throws IOException { 9 | int size = 5; 10 | int[] arr = new int[size]; 11 | getUserInput(arr, 0); 12 | display(arr); 13 | } 14 | 15 | // Recursive method to accept user input for the array 16 | public static void getUserInput(int[] arr, int current) throws IOException { 17 | System.out.print("Enter an Integer: "); 18 | String input = bf.readLine(); 19 | 20 | // Recursive case 21 | try { 22 | int num = Integer.parseInt(input); 23 | 24 | arr[current++] = num; 25 | getUserInput(arr, current); 26 | } 27 | // Detect improper inputs 28 | catch (NumberFormatException e) { 29 | System.out.println("Invalid input type"); 30 | getUserInput(arr, current); 31 | } 32 | // Base case 33 | catch (ArrayIndexOutOfBoundsException e) {} 34 | } 35 | 36 | // Display the array 37 | public static void display(int[] arr) { 38 | System.out.println("The array of integers is: "); 39 | for (int num : arr) { 40 | System.out.print(num + " "); 41 | } 42 | System.out.println(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Lab Test/2-Stack/Set A/Person.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Person implements Comparable { 4 | private final String name, gender, occupation; 5 | private final int age; 6 | private final static String[] occupation_list = {"doctor", "nurse", "teacher", "police"}; 7 | private boolean frontliner; 8 | 9 | public Person(String name, int age) { 10 | this(name, age, null, null); 11 | } 12 | 13 | public Person(String name, int age, String gender, String occupation) { 14 | this.name = name; 15 | this.age = age; 16 | this.gender = gender; 17 | this.occupation = occupation; 18 | setFrontliner(); 19 | } 20 | 21 | public int getAge() { 22 | return age; 23 | } 24 | 25 | public boolean getFrontliner() { 26 | return this.frontliner; 27 | } 28 | 29 | public void setFrontliner() { 30 | this.frontliner = isFrontliner(); 31 | } 32 | 33 | public boolean isFrontliner() { 34 | for (String o : occupation_list) { 35 | if (o.equals(this.occupation)) { 36 | return true; 37 | } 38 | } 39 | return false; 40 | } 41 | 42 | public int compareTo(Person p) { 43 | return Integer.compare(this.getAge(), p.getAge()); 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return String.format("%s %d %s %s\n", name, age, gender, isFrontliner() ? "Frontliner" : "Not frontliner"); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /L11-Tree/TestBST.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class TestBST { 4 | 5 | public static void main(String[] args) { 6 | BST tree = new BST<>(); 7 | 8 | Integer[] input = new Integer[] {45, 88, 54, 76, 98, 1, 2, 20, 6, 53, 42, 100, 86, 32, 28, 65, 14}; 9 | System.out.print("Input Data: "); 10 | for (Integer i : input) { 11 | tree.insert(i); 12 | System.out.print(i + " "); 13 | } 14 | System.out.println(); 15 | 16 | // Traverse tree 17 | System.out.print("Inorder (sorted): "); 18 | tree.inorder(); 19 | System.out.print("\nPostorder: "); 20 | tree.postorder(); 21 | System.out.print("\nPreorder: "); 22 | tree.preorder(); 23 | 24 | System.out.print("\nHeight of BST: " + tree.height()); 25 | 26 | System.out.print("\nRoot for BST is: " + tree.getRoot()); 27 | 28 | System.out.print("\nCheck whether 10 is in the tree? " + tree.search(10)); 29 | 30 | System.out.println("\nDelete 53"); 31 | tree.delete(53); 32 | 33 | System.out.print("Updated Inorder data (sorted): "); 34 | tree.inorder(); 35 | 36 | System.out.print("\nMin Value: " + tree.minValue()); 37 | System.out.print("\nMax Value: " + tree.maxValue()); 38 | 39 | System.out.print("\nA path from the root to 6 is: "); 40 | ArrayList> path = tree.path(6); 41 | for (TreeNode node : path) { 42 | System.out.print(node.element + " "); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /L01-OOP/Q2/TextFileReader.java: -------------------------------------------------------------------------------- 1 | import java.io.FileInputStream; 2 | import java.io.FileNotFoundException; 3 | import java.util.Scanner; 4 | import java.util.regex.Pattern; 5 | 6 | public class TextFileReader { 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.println("Filename -> Delimiters "); 10 | System.out.println("text1.txt -> ,"); 11 | System.out.println("text2.txt -> ,[space]"); 12 | System.out.println("text3.txt -> ;[space]"); 13 | System.out.println("text4.txt -> \\d+\n"); 14 | 15 | System.out.print("Enter txt file to read: "); 16 | String filename = input.nextLine(); 17 | 18 | System.out.print("Enter special characters (delimiter): "); 19 | String delimiter = input.nextLine(); 20 | 21 | try { 22 | Scanner inputStream = new Scanner(new FileInputStream(filename)); 23 | 24 | int charNum = 0; 25 | while (inputStream.hasNextLine()) { 26 | String line = inputStream.nextLine(); 27 | 28 | Pattern pattern = Pattern.compile(delimiter); 29 | String[] afterSplit = pattern.split(line); 30 | 31 | for (int i = 0; i < afterSplit.length; i++) { 32 | System.out.print(afterSplit[i]); 33 | charNum += afterSplit[i].length(); 34 | } 35 | System.out.println(); 36 | } 37 | System.out.println("\nNumber of characters : " + charNum); 38 | inputStream.close(); 39 | } catch (FileNotFoundException e) { 40 | System.out.println("File was not found!"); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Lab Test/2-Stack/Set A/Stack.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Stack { 4 | private final String stack_name; 5 | private final ArrayList list; 6 | 7 | public Stack(String stack_name) { 8 | this.stack_name = stack_name; 9 | this.list = new ArrayList<>(); 10 | } 11 | 12 | public void push(String name, int age) { 13 | list.add(new Person(name, age)); 14 | } 15 | 16 | public void push(String name, int age, String gender) { 17 | list.add(new Person(name, age, gender, null)); 18 | } 19 | 20 | public void push(String name, int age, String gender, String occupation) { 21 | list.add(new Person(name, age, gender, occupation)); 22 | } 23 | 24 | public void push(Person person) { 25 | list.add(person); 26 | } 27 | 28 | public Person pop() { 29 | return list.remove(this.getSize() - 1); 30 | } 31 | 32 | public Person peek() { 33 | return list.get(0); 34 | } 35 | 36 | public int getSize() { 37 | return list.size(); 38 | } 39 | 40 | public boolean isEmpty() { 41 | return list.isEmpty(); 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return "MyStack{" + 47 | "list=" + list.toString() + 48 | '}'; 49 | } 50 | 51 | public boolean search(Person o) { 52 | return list.contains(o); 53 | } 54 | 55 | public void displayStack() { 56 | System.out.println("----" + this.stack_name + "----\n"); 57 | if (isEmpty()) { 58 | System.out.println("Empty stack\n"); 59 | } 60 | else { 61 | for (int i = list.size() - 1; i >= 0; i--) { 62 | System.out.println(i + " " + list.get(i)); 63 | } 64 | } 65 | System.out.println("----------------------\n"); 66 | } 67 | } 68 | 69 | -------------------------------------------------------------------------------- /L01-OOP/Q3/Account.java: -------------------------------------------------------------------------------- 1 | import java.util.Date; 2 | 3 | class Account { 4 | private int id; 5 | private double balance, annualInterestRate; 6 | private final Date dateCreated; 7 | 8 | public Account() { 9 | this(0, 0); 10 | } 11 | 12 | public Account(int id, double balance) { 13 | this.id = id; 14 | this.balance = balance; 15 | dateCreated = new Date(); 16 | } 17 | 18 | public int getId() { 19 | return id; 20 | } 21 | 22 | public void setId(int id) { 23 | this.id = id; 24 | } 25 | 26 | public double getBalance() { 27 | return balance; 28 | } 29 | 30 | public void setBalance(double balance) { 31 | this.balance = balance; 32 | } 33 | 34 | public double getAnnualInterestRate() { 35 | return annualInterestRate; 36 | } 37 | 38 | public void setAnnualInterestRate(double annualInterestRate) { 39 | this.annualInterestRate = annualInterestRate; 40 | } 41 | 42 | public Date getDateCreated() { 43 | return dateCreated; 44 | } 45 | 46 | public double getMonthlyInterestRate() { 47 | return annualInterestRate / 12; 48 | } 49 | 50 | public double getMonthlyInterest() { 51 | return getMonthlyInterestRate() / 100 * balance; 52 | } 53 | 54 | public boolean withdraw(double amount) { 55 | if (amount <= balance) { 56 | balance -= amount; 57 | return true; 58 | } 59 | return false; 60 | } 61 | 62 | public double deposit(double amount) { 63 | balance += amount; 64 | return balance; 65 | } 66 | 67 | @Override 68 | public String toString() { 69 | return "Account{" + 70 | "id=" + id + 71 | ", balance=" + balance + 72 | ", annualInterestRate=" + annualInterestRate + 73 | ", dateCreated=" + dateCreated + 74 | '}'; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q1/SList/SList.java: -------------------------------------------------------------------------------- 1 | package SList; 2 | 3 | public class SList { 4 | private SNode head; 5 | private SNode tail; 6 | private int size; 7 | 8 | public SList() { 9 | head = null; 10 | tail = null; 11 | size = 0; 12 | } 13 | 14 | // Append a new element at the end of the list. 15 | public void appendEnd(E e) { 16 | if (tail == null) { 17 | tail = head = new SNode<>(e); 18 | } 19 | else { 20 | tail.next = new SNode<>(e); 21 | tail = tail.next; 22 | } 23 | size++; 24 | } 25 | 26 | // Eliminate the first element in the list. 27 | public E removeInitial() { 28 | if (size == 0) { 29 | return null; 30 | } 31 | 32 | SNode temp = head; 33 | head = head.next; 34 | if (head == null) { 35 | tail = null; 36 | } 37 | size--; 38 | return temp.element; 39 | } 40 | 41 | // Search for an element and returns true if this list contains the searched element 42 | public boolean contains(E e) { 43 | SNode current = head; 44 | while (current != null) { 45 | if ((current.element).equals(e)) { 46 | return true; 47 | } 48 | current = current.next; 49 | } 50 | return false; 51 | } 52 | 53 | // Empty all elements in the list and return a statement that reports that the list is empty. 54 | public void clear() { 55 | while (size > 0) { 56 | removeInitial(); 57 | } 58 | } 59 | 60 | // Display all values from the list in a successive order. 61 | public void display() { 62 | SNode current = head; 63 | while (current != null) { 64 | System.out.print(current.element + " "); 65 | current = current.next; 66 | } 67 | System.out.println(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /L03-ADTs and Bags/ArrayBagDemo.java: -------------------------------------------------------------------------------- 1 | public class ArrayBagDemo { 2 | 3 | public static void main(String[] args) { 4 | ArrayBag bag1 = new ArrayBag<>(); 5 | ArrayBag bag2 = new ArrayBag<>(); 6 | 7 | String[] contentOfBag1 = {"A", "A", "B", "A", "C", "A"}; 8 | String[] contentOfBag2 = {"A", "B", "A", "C", "B", "C", "D", "another string"}; 9 | 10 | System.out.println("bag1:"); 11 | testAdd(bag1, contentOfBag1); 12 | displayBag(bag1); 13 | System.out.println(); 14 | 15 | System.out.println("bag2:"); 16 | testAdd(bag2, contentOfBag2); 17 | displayBag(bag2); 18 | System.out.println(); 19 | 20 | System.out.println("bag3, test the method union of bag1 and bag2:"); 21 | ArrayBag bag3 = (ArrayBag) bag1.union(bag2); 22 | displayBag(bag3); 23 | System.out.println(); 24 | 25 | System.out.println("bag4, test the method intersection of bag1 and bag2:"); 26 | ArrayBag bag4 = (ArrayBag) bag1.intersection(bag2); 27 | displayBag(bag4); 28 | System.out.println(); 29 | 30 | System.out.println("bag5, test the method difference of bag1 and bag2:"); 31 | ArrayBag bag5 = (ArrayBag) bag1.difference(bag2); 32 | displayBag(bag5); 33 | } 34 | 35 | private static void testAdd(BagInterface aBag, String[] content) { 36 | System.out.print("Adding "); 37 | for (String item : content) { 38 | aBag.add(item); 39 | System.out.print(item + " "); 40 | } 41 | System.out.println(); 42 | } 43 | 44 | private static void displayBag(BagInterface aBag) { 45 | String[] bagContent = aBag.toArray(); 46 | System.out.printf("The bag contains %d string(s), as follows:\n", aBag.getCurrentSize()); 47 | for (int i = 0; i < aBag.getCurrentSize(); i++) { 48 | System.out.print(bagContent[i] + " "); 49 | } 50 | System.out.println(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /L04-Linked List/TestLinkedList.java: -------------------------------------------------------------------------------- 1 | public class TestLinkedList { 2 | 3 | public static void main(String[] args) { 4 | 5 | MyLinkedList myLinkedList = new MyLinkedList<>(); 6 | 7 | // append the following: a, b,c, d, e 8 | myLinkedList.addLast('a'); 9 | myLinkedList.addLast('b'); 10 | myLinkedList.addLast('c'); 11 | myLinkedList.addLast('d'); 12 | myLinkedList.addLast('e'); 13 | 14 | // print all the elements in the list 15 | System.out.print("All the elements in the list: "); 16 | myLinkedList.print(); 17 | 18 | // reverse all the elements in the list 19 | System.out.print("All the elements in the list in reverse order: "); 20 | myLinkedList.reverse(); 21 | 22 | // retrieve the number of elements in the list 23 | System.out.println( "Size: " + myLinkedList.getSize()); 24 | 25 | // retrieve the first and last value 26 | System.out.println("First element: " + myLinkedList.getFirst()); 27 | System.out.println("Last element : " + myLinkedList.getLast()); 28 | 29 | // delete middle value 30 | int first = myLinkedList.indexOf(myLinkedList.getFirst()); 31 | int last = myLinkedList.indexOf(myLinkedList.getLast()); 32 | int middle = (first + last) / 2; 33 | System.out.println("Middle value: " + myLinkedList.remove(middle)); 34 | 35 | // Retrieve the index location for the second and third value. 36 | System.out.println("Index of 2nd value: " + myLinkedList.indexOf('b')); 37 | System.out.println("Index of 3rd value: " + myLinkedList.indexOf('c')); 38 | 39 | // check if the list has the value c 40 | System.out.println("List has value 'c': " + myLinkedList.contains('c')); 41 | 42 | // Replace the items individually with the following: h,e,l,l,o. 43 | char[] letters = {'h', 'e', 'l', 'l', 'o'}; 44 | for (int i = 0; i < letters.length; i++) { 45 | myLinkedList.set(i, letters[i]); 46 | } 47 | myLinkedList.print(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q2/SinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | public class SinglyLinkedList { 2 | private SNode head; 3 | private SNode tail; 4 | private int size; 5 | 6 | public SinglyLinkedList() { 7 | } 8 | 9 | public void add(E e) { 10 | if (tail == null) { 11 | head = tail = new SNode<>(e); 12 | } 13 | else { 14 | tail.next = new SNode<>(e); 15 | tail = tail.next; 16 | } 17 | size++; 18 | } 19 | 20 | public void removeElement(E e) { 21 | if (size == 0) { 22 | throw new IllegalStateException(); 23 | } 24 | 25 | SNode current; 26 | if (head.element.equals(e)) { 27 | current = head; 28 | head = head.next; 29 | } 30 | else { 31 | SNode previous = head; 32 | while (!previous.next.element.equals(e)) { 33 | previous = previous.next; 34 | } 35 | current = previous.next; 36 | previous.next = current.next; 37 | } 38 | size--; 39 | System.out.println(current.element); 40 | } 41 | 42 | public void printList() { 43 | SNode current = head; 44 | String separator = ""; 45 | while (current != null) { 46 | System.out.print(separator + current.element); 47 | current = current.next; 48 | separator = ", "; 49 | } 50 | System.out.println("."); 51 | } 52 | 53 | public int getSize() { 54 | return size; 55 | } 56 | 57 | public boolean contains(E e) { 58 | SNode current = head; 59 | while (current != null) { 60 | if (current.element.equals(e)) { 61 | return true; 62 | } 63 | current = current.next; 64 | } 65 | return false; 66 | } 67 | 68 | public void replace(E e, E newE) { 69 | SNode current = head; 70 | while (!current.element.equals(e)) { 71 | current = current.next; 72 | } 73 | current.element = newE; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /L03-ADTs and Bags/BagInterface.java: -------------------------------------------------------------------------------- 1 | /** 2 | An interface that describes the operations of a bag of objects. 3 | */ 4 | public interface BagInterface 5 | { 6 | /** Gets the current number of entries in this bag. 7 | @return the integer number of entries currently in the bag */ 8 | public int getCurrentSize(); 9 | 10 | /** Sees whether this bag is full. 11 | @return true if the bag is full, or false if not */ 12 | public boolean isFull(); 13 | 14 | /** Sees whether this bag is empty. 15 | @return true if the bag is empty, or false if not */ 16 | public boolean isEmpty(); 17 | 18 | /** Adds a new entry to this bag. 19 | @param newEntry the object to be added as a new entry 20 | @return true if the addition is successful, or false if not */ 21 | public boolean add(T newEntry); 22 | 23 | /** Removes one unspecified entry from this bag, if possible. 24 | @return either the removed entry, if the removal was successful, 25 | or null */ 26 | public T remove(); 27 | 28 | /** Removes one occurrence of a given entry from this bag. 29 | @param anEntry the entry to be removed 30 | @return true if the removal was successful, or false if not */ 31 | public boolean remove(T anEntry); 32 | 33 | /** Removes all entries from this bag. */ 34 | public void clear(); 35 | 36 | /** Counts the number of times a given entry appears in this bag. 37 | @param anEntry the entry to be counted 38 | @return the number of times anEntry appears in the bag */ 39 | public int getFrequencyOf(T anEntry); 40 | 41 | /** Tests whether this bag contains a given entry. 42 | @param anEntry the entry to locate 43 | @return true if this bag contains anEntry, or false otherwise */ 44 | public boolean contains(T anEntry); 45 | 46 | /** Retrieves all entries that are in this bag. 47 | @return a newly allocated array of all the entries in the bag */ 48 | public T[] toArray(); 49 | 50 | /** 51 | @return a new bag contains all the items of both bags */ 52 | public BagInterface union(BagInterface aBag); 53 | 54 | /** 55 | @return a new bag */ 56 | public BagInterface intersection(BagInterface aBag); 57 | 58 | /** 59 | @return a new bag */ 60 | public BagInterface difference(BagInterface aBag); 61 | 62 | } // end BagInterface 63 | -------------------------------------------------------------------------------- /L01-OOP/Q1/ReadMyLetter_matricNum.java: -------------------------------------------------------------------------------- 1 | import java.io.FileInputStream; 2 | import java.io.FileNotFoundException; 3 | import java.io.FileOutputStream; 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | import java.util.Scanner; 7 | 8 | public class ReadMyLetter_matricNum { 9 | public static void main(String[] args) { 10 | // Part 1 11 | try { 12 | Scanner inputStream = new Scanner(new FileInputStream("name_matricNum.txt")); 13 | while (inputStream.hasNextLine()) { 14 | System.out.println(inputStream.nextLine()); 15 | } 16 | inputStream.close(); 17 | } catch (FileNotFoundException e) { 18 | System.out.println("File was not found!"); 19 | } 20 | System.out.println(""); 21 | 22 | 23 | // Part 2 24 | try { 25 | Scanner sc = new Scanner(System.in); 26 | String input; 27 | 28 | PrintWriter outputStream = new PrintWriter(new FileOutputStream("name_matricNum.txt", true)); 29 | outputStream.println("\n\nThursday, 18 June 2021.\n"); 30 | outputStream.print("It’s me again. Finally, it’s the end of the term and the DS class has finished! "); 31 | 32 | System.out.println("How you performed in the class?"); 33 | input = sc.nextLine(); 34 | // I think I performed moderately in the class. 35 | outputStream.println(input + ". "); 36 | 37 | System.out.println("\nAre you happy with your performance?"); 38 | input = sc.nextLine(); 39 | // I am happy with my performance 40 | outputStream.println(input + ". "); 41 | 42 | System.out.println("\nWhat has learning DS taught you / what did you learn from DS?"); 43 | input = sc.nextLine(); 44 | // I learn to use data structures in my program to organize the data 45 | outputStream.println(input + ". "); 46 | 47 | System.out.println("\nIs there any change to your target grade?"); 48 | input = sc.nextLine(); 49 | // No, my target grade still remains A 50 | outputStream.println(input + ". "); 51 | 52 | System.out.println("\nWhat you did well during the course?"); 53 | input = sc.nextLine(); 54 | // I love lab session because it gives me hands-on learning experience 55 | outputStream.println(input + ". "); 56 | 57 | System.out.println("\nWhat could have been done better during the course?"); 58 | input = sc.nextLine(); 59 | // I hope there is more hands-on learning session during the course 60 | outputStream.println(input + ". "); 61 | 62 | outputStream.close(); 63 | System.out.println("File saved!"); 64 | 65 | } catch (IOException e) { 66 | System.out.println("Problem with file output!"); 67 | } 68 | } 69 | } 70 | 71 | -------------------------------------------------------------------------------- /L01-OOP/Q4/Account.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Date; 3 | 4 | class Account { 5 | private String name; 6 | private int id; 7 | private double balance, annualInterestRate; 8 | private final Date dateCreated; 9 | private final ArrayList transactions; 10 | 11 | public Account() { 12 | this(null, 0, 0); 13 | } 14 | 15 | public Account(int id, double balance) { 16 | this(null, id, balance); 17 | } 18 | 19 | public Account(String name, int id, double balance) { 20 | this.name = name; 21 | this.id = id; 22 | this.balance = balance; 23 | dateCreated = new Date(); 24 | transactions = new ArrayList<>(); 25 | } 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public void setName(String name) { 31 | this.name = name; 32 | } 33 | 34 | public int getId() { 35 | return id; 36 | } 37 | 38 | public void setId(int id) { 39 | this.id = id; 40 | } 41 | 42 | public double getBalance() { 43 | return balance; 44 | } 45 | 46 | public void setBalance(double balance) { 47 | this.balance = balance; 48 | } 49 | 50 | public double getAnnualInterestRate() { 51 | return annualInterestRate; 52 | } 53 | 54 | public void setAnnualInterestRate(double annualInterestRate) { 55 | this.annualInterestRate = annualInterestRate; 56 | } 57 | 58 | public Date getDateCreated() { 59 | return dateCreated; 60 | } 61 | 62 | public double getMonthlyInterestRate() { 63 | return annualInterestRate / 12; 64 | } 65 | 66 | public double getMonthlyInterest() { 67 | return getMonthlyInterestRate() / 100 * balance; 68 | } 69 | 70 | public boolean withdraw(double amount) { 71 | if (amount <= balance) { 72 | balance -= amount; 73 | transactions.add(new Transaction('W', amount, balance, "Withdraw")); 74 | return true; 75 | } 76 | return false; 77 | } 78 | 79 | public double deposit(double amount) { 80 | balance += amount; 81 | transactions.add(new Transaction('W', amount, balance, "Deposit")); 82 | return balance; 83 | } 84 | 85 | @Override 86 | public String toString() { 87 | StringBuilder str = new StringBuilder(String.format("Account Summary\n\nHolder Name: %s\nInterest Rate: %.2f %%\nBalance: %.2f\n", name, annualInterestRate, balance)); 88 | str.append(String.format("Transaction History:\n%-30s %5s %10s %10s %15s\n", "Date", "Type", "Amount", "Balance", "Description")); 89 | 90 | for (Transaction transaction : transactions) { 91 | str.append(String.format("%-30s %5s %10.2f %10.2f %15s\n", 92 | dateCreated, transaction.getType(), transaction.getAmount(), 93 | transaction.getBalance(), transaction.getDescription())); 94 | } 95 | return str.toString(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /L08-Graph/TestWeightedGraph.java: -------------------------------------------------------------------------------- 1 | package Lab.L8; 2 | 3 | public class TestWeightedGraph { 4 | 5 | public static void main(String[] args) { 6 | WeightedGraph graph1 = new WeightedGraph<>(); 7 | String[] cities = {"Alor Setar", "Kuching", "Langkawi", "Melaka", "Penang", "Tawau"}; 8 | for (String city : cities) { 9 | graph1.addVertex(city); 10 | } 11 | 12 | System.out.println("The number of vertices in graph1: " + graph1.getSize()); 13 | 14 | System.out.println("Cities and their vertices "); 15 | for (int i = 0; i < graph1.getSize(); i++) { 16 | System.out.printf("%d: %s\t", i, graph1.getVertex(i)); 17 | } 18 | System.out.println(); 19 | 20 | System.out.println("Is Melaka in the Graph? " + graph1.hasVertex("Melaka")); 21 | System.out.println("Is Ipoh in the Graph? " + graph1.hasVertex("Ipoh")); 22 | System.out.println(); 23 | 24 | System.out.println("Kuching at index: " + graph1.getIndex("Kuching")); 25 | System.out.println("Ipoh at index: " + graph1.getIndex("Ipoh")); 26 | System.out.println(); 27 | 28 | System.out.println("add edge Kuching - Melaka: " + graph1.addEdge("Kuching", "Melaka", 800)); 29 | System.out.println("add edge Langkawi - Penang: " + graph1.addEdge("Langkawi", "Penang", 100)); 30 | System.out.println("add edge Melaka - Penang: " + graph1.addEdge("Melaka", "Penang", 400)); 31 | System.out.println("add edge Alor Setar - Kuching: " + graph1.addEdge("Alor Setar", "Kuching", 1200)); 32 | System.out.println("add edge Tawau - Alor Setar: " + graph1.addEdge("Tawau", "Alor Setar", 1900)); 33 | System.out.println("add edge Kuching - Tawau: " + graph1.addEdge("Kuching", "Tawau", 900)); 34 | System.out.println("add edge Langkawi - Ipoh: " + graph1.addEdge("Langkawi", "Ipoh", 200)); 35 | System.out.println(); 36 | 37 | System.out.println("has edge from Kuching to Melaka? " + graph1.hasEdge("Kuching", "Melaka")); 38 | System.out.println("has edge from Melaka to Langkawi? " + graph1.hasEdge("Melaka", "Langkawi")); 39 | System.out.println("has edge from Ipoh to Langkawi? " + graph1.hasEdge("Ipoh", "Langkawi")); 40 | System.out.println(); 41 | 42 | System.out.println("Weight of the edge from Kuching to Melaka? " + graph1.getEdgeWeight("Kuching", "Melaka")); 43 | System.out.println("Weight of the edge from Tawau to Alor Setar? " + graph1.getEdgeWeight("Tawau", "Alor Setar")); 44 | System.out.println("Weight of the edge from Semporna to Ipoh? " + graph1.getEdgeWeight("Semporna", "Ipoh")); 45 | System.out.println(); 46 | 47 | System.out.printf("In and out degree for Kuching is %d and %d\n", graph1.getIndeg("Kuching"), graph1.getOutdeg("Kuching")); 48 | System.out.printf("In and out degree for Penang is %d and %d\n", graph1.getIndeg("Penang"), graph1.getOutdeg("Penang")); 49 | System.out.printf("In and out degree for Ipoh is %d and %d\n", graph1.getIndeg("Ipoh"), graph1.getOutdeg("Ipoh")); 50 | System.out.println(); 51 | 52 | System.out.println("Neighbours of Kuching: " + graph1.getNeighbours("Kuching")); 53 | System.out.println("\nPrint Edges: "); 54 | graph1.printEdges(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /L08-Graph/TestGraph.java: -------------------------------------------------------------------------------- 1 | package Lab.L8; 2 | 3 | import java.util.LinkedList; 4 | 5 | public class TestGraph { 6 | 7 | public static void main(String[] args) { 8 | LinkedList> graph = new LinkedList<>(); 9 | Graph graph1 = new Graph<>(); 10 | String[] cities = {"Alor Setar", "Kuching", "Langkawi", "Melaka", "Penang", "Tawau"}; 11 | for (String city : cities) { 12 | graph1.addVertex(city); 13 | } 14 | 15 | System.out.println("The number of vertices in graph1: " + graph1.getSize()); 16 | 17 | System.out.println("Cities and their vertices "); 18 | for (int i = 0; i < graph1.getSize(); i++) { 19 | System.out.printf("%d: %s\t", i, graph1.getVertex(i)); 20 | } 21 | System.out.println(); 22 | 23 | System.out.println("Is Melaka in the Graph? " + graph1.hasVertex("Melaka")); 24 | System.out.println("Is Ipoh in the Graph? " + graph1.hasVertex("Ipoh")); 25 | System.out.println(); 26 | 27 | System.out.println("Kuching at index: " + graph1.getIndex("Kuching")); 28 | System.out.println("Ipoh at index: " + graph1.getIndex("Ipoh")); 29 | System.out.println(); 30 | 31 | System.out.println("add edge Kuching - Melaka: " + graph1.addEdge("Kuching", "Melaka")); 32 | System.out.println("add edge Langkawi - Penang: " + graph1.addEdge("Langkawi", "Penang")); 33 | System.out.println("add edge Melaka - Penang: " + graph1.addEdge("Melaka", "Penang")); 34 | System.out.println("add edge Alor Setar - Kuching: " + graph1.addEdge("Alor Setar", "Kuching")); 35 | System.out.println("add edge Tawau - Alor Setar: " + graph1.addEdge("Tawau", "Alor Setar")); 36 | System.out.println("add edge Kuching - Tawau: " + graph1.addEdge("Kuching", "Tawau")); 37 | System.out.println("add edge Langkawi - Ipoh: " + graph1.addEdge("Langkawi", "Ipoh")); 38 | System.out.println(); 39 | 40 | System.out.println("has edge from Kuching to Melaka? " + graph1.hasEdge("Kuching", "Melaka")); 41 | System.out.println("has edge from Melaka to Langkawi? " + graph1.hasEdge("Melaka", "Langkawi")); 42 | System.out.println("has edge from Ipoh to Langkawi? " + graph1.hasEdge("Ipoh", "Langkawi")); 43 | System.out.println(); 44 | 45 | System.out.println("Weight of the edge from Kuching to Melaka? " + graph1.getEdgeWeight("Kuching", "Melaka")); 46 | System.out.println("Weight of the edge from Tawau to Alor Setar? " + graph1.getEdgeWeight("Tawau", "Alor Setar")); 47 | System.out.println("Weight of the edge from Semporna to Ipoh? " + graph1.getEdgeWeight("Semporna", "Ipoh")); 48 | System.out.println(); 49 | 50 | System.out.printf("In and out degree for Kuching is %d and %d\n", graph1.getIndeg("Kuching"), graph1.getOutdeg("Kuching")); 51 | System.out.printf("In and out degree for Penang is %d and %d\n", graph1.getIndeg("Penang"), graph1.getOutdeg("Penang")); 52 | System.out.printf("In and out degree for Ipoh is %d and %d\n", graph1.getIndeg("Ipoh"), graph1.getOutdeg("Ipoh")); 53 | System.out.println(); 54 | 55 | System.out.println("Neighbours of Kuching: " + graph1.getNeighbours("Kuching")); 56 | System.out.println("\nPrint Edges: "); 57 | graph1.printEdges(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q2/StudentManagementSystem.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class StudentManagementSystem { 4 | 5 | public static void main(String[] args) { 6 | Scanner scanner = new Scanner(System.in); 7 | SinglyLinkedList singlyLinkedList = new SinglyLinkedList<>(); 8 | 9 | System.out.println("Enter your student name list. Enter 'n' to end....."); 10 | String input; 11 | while (true) { 12 | input = scanner.nextLine(); 13 | if (input.equalsIgnoreCase("n")) { 14 | break; 15 | } 16 | singlyLinkedList.add(input); 17 | } 18 | 19 | System.out.println("\nYou have entered the following students' name :"); 20 | singlyLinkedList.printList(); 21 | 22 | System.out.println("\nThe number of students entered is : " + singlyLinkedList.getSize()); 23 | 24 | while (true) { 25 | System.out.println("\nAll the names entered are correct? Enter 'r' to rename the student name, 'n' to proceed"); 26 | input = scanner.nextLine(); 27 | if (input.equalsIgnoreCase("r")) { 28 | System.out.println("\nEnter the existing student name that u want to rename :"); 29 | String oldName = scanner.nextLine(); 30 | 31 | if (singlyLinkedList.contains(oldName)) { 32 | System.out.println("\nEnter the new name :"); 33 | String newName = scanner.nextLine(); 34 | singlyLinkedList.replace(oldName, newName); 35 | } 36 | else { 37 | System.out.println("Student name does not exist! Please enter another name!"); 38 | } 39 | } 40 | else if (input.equalsIgnoreCase("n")) { 41 | break; 42 | } 43 | else { 44 | System.out.println("Invalid Input! Enter 'r' or 'n' only!"); 45 | } 46 | } 47 | System.out.println("\nThe new student list is :"); 48 | singlyLinkedList.printList(); 49 | 50 | while (true) { 51 | System.out.println("\nDo you want to remove any of your student name? Enter 'y' for yes, 'n' to proceed."); 52 | input = scanner.nextLine(); 53 | 54 | if (input.equalsIgnoreCase("y")) { 55 | System.out.println("\nEnter a student name to remove :"); 56 | String nameToRemove = scanner.nextLine(); 57 | if (singlyLinkedList.contains(nameToRemove)) { 58 | singlyLinkedList.removeElement(nameToRemove); 59 | } 60 | else { 61 | System.out.println("Student name does not exist! Please enter another name!"); 62 | } 63 | } 64 | else if (input.equalsIgnoreCase("n")) { 65 | break; 66 | } 67 | else { 68 | System.out.println("Invalid Input! Enter 'y' for yes and 'n' for no!"); 69 | } 70 | } 71 | 72 | System.out.println("\nThe number of updated student is :" + singlyLinkedList.getSize()); 73 | 74 | System.out.println("The updated students list is :"); 75 | singlyLinkedList.printList(); 76 | 77 | System.out.println("\nAll the student data captured complete. Thank you!"); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Lab Test/2-Stack/Set A/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | //---------------- Part A ---------------- 4 | Stack raw = new Stack("Raw list"); 5 | raw.push("ali",32,"m","doctor"); 6 | raw.push("lisa",29,"f","nurse"); 7 | raw.push("tanaka",41); 8 | raw.push("ahmad",18,"m","developer"); 9 | raw.push("maria",20,"f","accountant"); 10 | raw.push("chong",70,"m","lawyer"); 11 | raw.push("raju",55,"m","police"); 12 | raw.push("alex",16,"f","business man "); 13 | Person katie = new Person("katie",36,"f","teacher"); 14 | raw.push(katie); 15 | raw.displayStack(); 16 | 17 | 18 | //--------------- Part B --------------- 19 | Stack frontliners = new Stack("Frontliners"); 20 | Stack others = new Stack("Others"); 21 | 22 | System.out.println("\n~~~~~~Sort into frontliners and others~~~~~~\n"); 23 | while (!raw.isEmpty()) { 24 | Person personToCheck = raw.pop(); 25 | if (personToCheck.getFrontliner()) { 26 | frontliners.push(personToCheck); 27 | } 28 | else { 29 | others.push(personToCheck); 30 | } 31 | } 32 | raw.displayStack(); 33 | frontliners.displayStack(); 34 | others.displayStack(); 35 | 36 | 37 | //--------------- Part C --------------- 38 | Stack priority = new Stack("Vaccine Priority List"); 39 | System.out.println("\n~~~~~Sort into vaccine list~~~~~\n"); 40 | 41 | sortStack(frontliners, others, priority); 42 | 43 | others.displayStack(); 44 | frontliners.displayStack(); 45 | priority.displayStack(); 46 | } 47 | 48 | /** 49 | * Sort the people to get vaccinated according to their priority in ascending order. 50 | * 51 | * Criteria: 52 | * - Frontliner has higher priority than non-frontliner 53 | * - The higher the age of a person, the higher the priority 54 | */ 55 | public static void bubbleSort(Person[] people) { 56 | boolean nextPass = true; 57 | for (int p = 1; p < people.length && nextPass; p++) { 58 | nextPass = false; 59 | for (int i = 0; i < people.length - p; i++) { 60 | if (people[i].compareTo(people[i + 1]) > 0) { 61 | // Swap people[i] and people[i + 1] 62 | Person temp = people[i]; 63 | people[i] = people[i + 1]; 64 | people[i + 1] = temp; 65 | nextPass = true; 66 | } 67 | } 68 | } 69 | } 70 | 71 | /** 72 | * Sort the frontliners and others into a priority stack 73 | */ 74 | public static void sortStack(Stack frontliners, Stack others, Stack priority) { 75 | Person[] sortOthers = new Person[others.getSize()]; 76 | Person[] sortFrontliners = new Person[frontliners.getSize()]; 77 | 78 | // load others into array 79 | int index = 0; 80 | while (!others.isEmpty()) { 81 | sortOthers[index++] = others.pop(); 82 | } 83 | 84 | // load frontliners into array 85 | index = 0; 86 | while (!frontliners.isEmpty()) { 87 | sortFrontliners[index++] = frontliners.pop(); 88 | } 89 | 90 | bubbleSort(sortOthers); 91 | bubbleSort(sortFrontliners); 92 | 93 | // Push others into priority stack 94 | for (Person p : sortOthers) { 95 | priority.push(p); 96 | } 97 | 98 | // Push frontliners into priority stack 99 | for (Person p : sortFrontliners) { 100 | priority.push(p); 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /L07-Queue/Q3/Trading.java: -------------------------------------------------------------------------------- 1 | import MyQueue; 2 | import java.util.Scanner; 3 | 4 | public class Trading { 5 | 6 | public static void main(String[] args) { 7 | Scanner scanner = new Scanner(System.in); 8 | MyQueue shareQ = new MyQueue<>(); 9 | MyQueue priceQ = new MyQueue<>(); 10 | 11 | int capitalGainLoss = 0; 12 | while (true) { 13 | System.out.print("Enter your query (In format 'Buy / Sell x shares at $y each'): "); 14 | String input = scanner.nextLine(); 15 | 16 | // Break if nothing is entered 17 | if (input.isEmpty()) { 18 | break; 19 | } 20 | else { 21 | String[] tokens = input.split(" "); 22 | String buySell = tokens[0]; 23 | String numOfShare = tokens[1]; 24 | String buySellPrice = tokens[4].replace("$", ""); 25 | 26 | if (buySell.equalsIgnoreCase("Sell")) { 27 | System.out.println("Selling the share now..."); 28 | int shareToSell = Integer.parseInt(numOfShare); 29 | 30 | int remainingShare = 0; 31 | do { 32 | if (!shareQ.isEmpty()) { 33 | int share = Integer.parseInt(shareQ.dequeue()); 34 | int price = Integer.parseInt(priceQ.dequeue()); 35 | 36 | // Sufficient share to sell for the enqueued value 37 | if (share >= shareToSell) { 38 | capitalGainLoss = capitalGainLoss + shareToSell * (Integer.parseInt(buySellPrice) - price); 39 | remainingShare = share - shareToSell; 40 | 41 | // Re-insert remaining shares after selling back to queue 42 | if (remainingShare > 0) { 43 | insertRemaining(shareQ, remainingShare); 44 | insertRemaining(priceQ, price); 45 | } 46 | 47 | } 48 | // Not enough share to sell for the enqueued value 49 | else { 50 | capitalGainLoss = capitalGainLoss + share * (Integer.parseInt(buySellPrice) - price); 51 | } 52 | 53 | System.out.println("Total Capital Gain / Loss: " + capitalGainLoss); 54 | shareToSell = shareToSell - share; 55 | } 56 | else { 57 | System.out.println("No share to sell!"); 58 | shareToSell = 0; 59 | } 60 | 61 | } while (shareToSell > 0); 62 | } 63 | else if (buySell.equalsIgnoreCase("Buy")) { 64 | System.out.println("Buying now..."); 65 | shareQ.enqueue(numOfShare); 66 | priceQ.enqueue(buySellPrice); 67 | } 68 | else { 69 | System.out.println("Invalid Input!"); 70 | continue; 71 | } 72 | 73 | // Display current queue content 74 | System.out.println("Queue for Share: " + shareQ); 75 | System.out.println("Queue for Price: " + priceQ); 76 | System.out.println(); 77 | } 78 | } 79 | 80 | System.out.println("Final Capital Gain / Loss: " + capitalGainLoss); 81 | } 82 | 83 | public static void insertRemaining(MyQueue queue, int remaining) { 84 | MyQueue temp = new MyQueue<>(); 85 | temp.enqueue(Integer.toString(remaining)); 86 | while (!queue.isEmpty()) { 87 | temp.enqueue(queue.dequeue()); 88 | } 89 | while (!temp.isEmpty()) { 90 | queue.enqueue(temp.dequeue()); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /L06-Stack/Q5/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Stack; 3 | 4 | /* 5 | NUmber of disks = n 6 | Number of moves = 2^n - 1 7 | 8 | S - source 9 | A - auxiliary 10 | D - destination 11 | 12 | If n is odd 13 | | | | 14 | S A D 15 | else 16 | | | | 17 | S D A 18 | */ 19 | public class TowerOfHanoi { 20 | static Stack source; 21 | static Stack auxiliary; 22 | static Stack destination; 23 | static int disks; 24 | 25 | public static void main(String[] args) { 26 | source = new Stack<>(); 27 | auxiliary = new Stack<>(); 28 | destination = new Stack<>(); 29 | 30 | // prompt users for number of disks 31 | Scanner scanner = new Scanner(System.in); 32 | System.out.print("Enter number of disk(s): "); 33 | disks = scanner.nextInt(); 34 | 35 | // swap D and A poles when number of disks is even 36 | if (disks % 2 == 0) { 37 | Stack temp = destination; 38 | destination = auxiliary; 39 | auxiliary = temp; 40 | } 41 | 42 | // add disks to the source rod 43 | for (int i = disks; i > 0; i--) { 44 | source.push(new Disk(i)); 45 | } 46 | 47 | // determine total number of moves required to get solution 48 | int moves = (int) Math.pow(2, disks) - 1; 49 | 50 | for (int i = 1; i <= moves; i++) { 51 | if (i % 3 == 1) { // S <-> D 52 | moveDisksBetween(source, destination); 53 | } 54 | else if (i % 3 == 2) { // S <-> A 55 | moveDisksBetween(source, auxiliary); 56 | } 57 | else if (i % 3 == 0) { // A <-> D 58 | moveDisksBetween(auxiliary, destination); 59 | } 60 | display(); 61 | } 62 | } 63 | 64 | public static void moveDisksBetween(Stack src, Stack dest) { 65 | Disk srcPoleTopDisk = null; 66 | Disk destPoleTopDisk = null; 67 | 68 | if (!src.isEmpty()) { 69 | srcPoleTopDisk = src.pop(); 70 | } 71 | if (!dest.isEmpty()) { 72 | destPoleTopDisk = dest.pop(); 73 | } 74 | 75 | // source pole is empty 76 | if (srcPoleTopDisk == null) { 77 | src.push(destPoleTopDisk); 78 | } 79 | // destination pole is empty 80 | else if (destPoleTopDisk == null) { 81 | dest.push(srcPoleTopDisk); 82 | } 83 | // src pole top disk > dest pole top disk 84 | else if (srcPoleTopDisk.getSize() > destPoleTopDisk.getSize()) { 85 | // add the disk back to the original pole 86 | src.push(srcPoleTopDisk); 87 | // move from dest to src 88 | src.push(destPoleTopDisk); 89 | } 90 | // src pole top disk < dest pole top disk 91 | else { 92 | dest.push(destPoleTopDisk); 93 | dest.push(srcPoleTopDisk); 94 | } 95 | } 96 | 97 | public static void display() { 98 | System.out.println(" A | B | C"); 99 | System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐"); 100 | for(int i = disks - 1; i >= 0; i--) { 101 | String d1 = " ", d2 = " ", d3 = " "; 102 | try { 103 | d1 = String.valueOf(source.get(i)); 104 | } 105 | catch (Exception e) {} 106 | 107 | try { 108 | d2 = String.valueOf(auxiliary.get(i)); 109 | } 110 | catch (Exception e) {} 111 | 112 | try { 113 | d3 = String.valueOf(destination.get(i)); 114 | } 115 | catch (Exception e) {} 116 | 117 | System.out.println(" " + d1 + " | " + d2 +" | "+ d3); 118 | } 119 | System.out.println("\n"); 120 | 121 | Scanner sc = new Scanner(System.in); 122 | System.out.println("Press 'Enter' to continue!"); 123 | sc.nextLine(); 124 | } 125 | } -------------------------------------------------------------------------------- /L05-Doubly Linked List/Q3/DoublyLinkedList.java: -------------------------------------------------------------------------------- 1 | import java.util.NoSuchElementException; 2 | 3 | public class DoublyLinkedList { 4 | private DNode head; 5 | private DNode tail; 6 | private int size; 7 | 8 | public DoublyLinkedList() { 9 | } 10 | 11 | public void addFirst(E e) { 12 | DNode temp = new DNode<>(e, head, null); 13 | if (head != null) { 14 | head.prev = temp; 15 | } 16 | head = temp; 17 | if (tail == null) { 18 | tail = temp; 19 | } 20 | size++; 21 | System.out.println("Adding: " + e); 22 | } 23 | 24 | public void addLast(E e) { 25 | DNode temp = new DNode<>(e, null, tail); 26 | if (tail != null) { 27 | tail.next = temp; 28 | } 29 | tail = temp; 30 | if (head == null) { 31 | head = temp; 32 | } 33 | size++; 34 | System.out.println("Adding: " + e); 35 | } 36 | 37 | public void add(int index, E e) { 38 | if (index < 0 || index > size) { 39 | throw new IndexOutOfBoundsException(); 40 | } 41 | else if (index == 0) { 42 | addFirst(e); 43 | } 44 | else if (index == size) { 45 | addLast(e); 46 | } 47 | else { 48 | DNode temp = head; 49 | for (int i = 0; i < index; i++) { 50 | temp = temp.next; 51 | } 52 | DNode insert = new DNode<>(e, temp, temp.prev); 53 | temp.prev.next = insert; 54 | temp.prev = insert; 55 | size++; 56 | System.out.println("Adding: " + e); 57 | } 58 | } 59 | 60 | public E removeFirst() { 61 | if (size == 0) { 62 | throw new NoSuchElementException(); 63 | } 64 | DNode temp = head; 65 | head = head.next; 66 | head.prev = null; 67 | size--; 68 | System.out.println("Deleted: " + temp.element); 69 | return temp.element; 70 | } 71 | 72 | public E removeLast() { 73 | if (size == 0) { 74 | throw new NoSuchElementException(); 75 | } 76 | DNode temp = tail; 77 | tail = tail.prev; 78 | tail.next = null; 79 | size--; 80 | System.out.println("Deleted: " + temp.element); 81 | return temp.element; 82 | } 83 | 84 | public E remove(int index) { 85 | if (index < 0 || index >= size) { 86 | throw new IndexOutOfBoundsException(); 87 | } 88 | else if (index == 0) { 89 | return removeFirst(); 90 | } 91 | else if (index == size - 1) { 92 | return removeLast(); 93 | } 94 | else { 95 | DNode current = head; 96 | for (int i = 0; i < index; i++) { 97 | current = current.next; 98 | } 99 | E element = current.element; 100 | current.prev.next = current.next; 101 | current.next.prev = current.prev; 102 | current.prev = null; 103 | current.next = null; 104 | size--; 105 | System.out.println("Deleted: " + element); 106 | return element; 107 | } 108 | } 109 | 110 | public void traverseForward() { 111 | System.out.println("Iterating forward.."); 112 | DNode current = head; 113 | while (current != null) { 114 | System.out.print(current.element + " "); 115 | current = current.next; 116 | } 117 | System.out.println(); 118 | } 119 | 120 | public void traverseBackward() { 121 | System.out.println("Iterating backward.."); 122 | DNode current = tail; 123 | while (current != null) { 124 | System.out.print(current.element + " "); 125 | current = current.prev; 126 | } 127 | System.out.println(); 128 | } 129 | 130 | public int getSize() { 131 | return size; 132 | } 133 | 134 | public void clear() { 135 | int count = 0; 136 | DNode temp; 137 | while (head != null) { 138 | temp = head.next; 139 | head.next = head.prev = null; 140 | head = temp; 141 | count++; 142 | } 143 | tail.next = tail.prev = null; 144 | size = 0; 145 | System.out.println("Successfully clear " + count + " node(s)"); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /L03-ADTs and Bags/ArrayBag.java: -------------------------------------------------------------------------------- 1 | public class ArrayBag implements BagInterface { 2 | private static final int DEFAULT_CAPACITY = 25; 3 | private T[] bag; 4 | private int numberOfEntries; 5 | 6 | public ArrayBag() { 7 | this(DEFAULT_CAPACITY); 8 | } 9 | 10 | public ArrayBag(int capacity) { 11 | if (capacity <= 0) { 12 | throw new IllegalArgumentException("Capacity must be greater than 0"); 13 | } 14 | 15 | @SuppressWarnings("unchecked") 16 | T[] tempBag = (T[]) new Object[capacity]; 17 | bag = tempBag; 18 | } 19 | 20 | @Override 21 | public int getCurrentSize() { 22 | return numberOfEntries; 23 | } 24 | 25 | @Override 26 | public boolean isFull() { 27 | return (numberOfEntries >= bag.length); 28 | } 29 | 30 | @Override 31 | public boolean isEmpty() { 32 | return (numberOfEntries == 0); 33 | } 34 | 35 | @Override 36 | public boolean add(T newEntry) { 37 | if (newEntry == null) { 38 | throw new IllegalArgumentException("New entry must not be null"); 39 | } 40 | else if (!isFull()) { 41 | bag[numberOfEntries] = newEntry; 42 | numberOfEntries++; 43 | return true; 44 | } 45 | return false; 46 | } 47 | 48 | @Override 49 | public T remove() { 50 | T result = null; 51 | if (!isEmpty()) { 52 | result = bag[numberOfEntries - 1]; 53 | bag[numberOfEntries - 1] = null; 54 | numberOfEntries--; 55 | } 56 | return result; 57 | } 58 | 59 | @Override 60 | public boolean remove(T anEntry) { 61 | if (!isEmpty()) { 62 | for (int i = 0; i < numberOfEntries; i++) { 63 | if (bag[i].equals(anEntry)) { 64 | // shift remaining items left by one 65 | for (int j = i; j < numberOfEntries - 1; j++) { 66 | bag[j] = bag[j+1]; 67 | } 68 | 69 | bag[numberOfEntries - 1] = null; 70 | numberOfEntries--; 71 | return true; 72 | } 73 | } 74 | } 75 | return false; 76 | } 77 | 78 | @Override 79 | public void clear() { 80 | while (!isEmpty()) { 81 | remove(); 82 | } 83 | } 84 | 85 | @Override 86 | public int getFrequencyOf(T anEntry) { 87 | int count = 0; 88 | for (int i = 0; i < numberOfEntries; i++) { 89 | if (bag[i].equals(anEntry)) { 90 | count++; 91 | } 92 | } 93 | return count; 94 | } 95 | 96 | @Override 97 | public boolean contains(T anEntry) { 98 | if (!isEmpty()) { 99 | for (int i = 0; i < numberOfEntries; i++) { 100 | if (bag[i].equals(anEntry)) { 101 | return true; 102 | } 103 | } 104 | } 105 | return false; 106 | } 107 | 108 | @Override 109 | public T[] toArray() { 110 | @SuppressWarnings("unchecked") 111 | T[] result = (T[]) new Object[numberOfEntries]; 112 | for (int i = 0; i < numberOfEntries; i++) { 113 | result[i] = bag[i]; 114 | } 115 | return result; 116 | } 117 | 118 | // Q2 119 | @Override 120 | public BagInterface union(BagInterface aBag) { 121 | T[] bagA = this.toArray(); 122 | T[] bagB = aBag.toArray(); 123 | 124 | int totalSize = bagA.length + bagB.length; 125 | ArrayBag unionBag = new ArrayBag<>(totalSize); 126 | 127 | for (int i = 0; i < bagA.length; i++) { 128 | unionBag.add(bagA[i]); 129 | } 130 | 131 | for (int i = 0; i < bagB.length; i++) { 132 | unionBag.add(bagB[i]); 133 | } 134 | return unionBag; 135 | } 136 | 137 | // Q3 138 | @Override 139 | public BagInterface intersection(BagInterface aBag) { 140 | T[] bagA = this.toArray(); 141 | T[] bagB = aBag.toArray(); 142 | ArrayBag intersectionBag = new ArrayBag<>(bagA.length); 143 | 144 | for (int i = 0; i < bagA.length; i++) { 145 | for (int j = 0; j < bagB.length; j++) { 146 | if (bagA[i].equals(bagB[j])) { 147 | intersectionBag.add(bagB[j]); 148 | bagB[j] = null; 149 | break; // go to next loop 150 | } 151 | } 152 | } 153 | return intersectionBag; 154 | } 155 | 156 | // Q4 157 | @Override 158 | public BagInterface difference(BagInterface aBag) { 159 | T[] bagA = this.toArray(); 160 | T[] bagB = aBag.toArray(); 161 | ArrayBag differenceBag = new ArrayBag<>(bagA.length); 162 | 163 | // set duplicate items to null 164 | for (int i = 0; i < bagA.length; i++) { 165 | for (int j = 0; j < bagB.length; j++) { 166 | if (bagA[i].equals(bagB[j])) { 167 | bagA[i] = null; 168 | bagB[j] = null; 169 | break; 170 | } 171 | } 172 | } 173 | 174 | for (int i = 0; i < bagA.length; i++) { 175 | if (bagA[i] != null) { 176 | differenceBag.add(bagA[i]); 177 | } 178 | } 179 | return differenceBag; 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /Lab Test/1-OOP/Set A/ShoppingMall.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class ShoppingMall { 4 | 5 | public static void main(String[] args) { 6 | //--------------------------- FoodStore --------------------------- 7 | 8 | // McDonalds 9 | FoodStore mcDonalds = new FoodStore("McDonalds", new Person("Mike", "0101122334")); 10 | mcDonalds.addMenu("Burger", 10); 11 | mcDonalds.addMenu("Fried Chicken", 12); 12 | String[] mcDonaldsEmployees = {"Jack", "Jane"}; 13 | mcDonalds.addEmployee(mcDonaldsEmployees); 14 | 15 | // Sushi Mentai 16 | FoodStore sushiMentai = new FoodStore("Sushi Mentai", new Person("Max", "0112233445")); 17 | sushiMentai.addMenu("Chicken Katsu Don", 15); 18 | sushiMentai.addMenu("Ramen", 12); 19 | String[] sushiMentaiEmployees = {"Adam", "Alex", "Andrew"}; 20 | sushiMentai.addEmployee(sushiMentaiEmployees); 21 | 22 | // Warong Penyet 23 | FoodStore waroengPenyet = new FoodStore("Waroeng Penyet", new Person("Mike", "0101122334")); 24 | waroengPenyet.addMenu("Burger", 10); 25 | waroengPenyet.addMenu("Fried Chicken", 12); 26 | String[] waroengPenyetEmployees = {"Lex", "Leon"}; 27 | waroengPenyet.addEmployee(waroengPenyetEmployees); 28 | 29 | FoodStore[] foodStores = {mcDonalds, sushiMentai, waroengPenyet}; 30 | 31 | //--------------------------- FashionStore --------------------------- 32 | 33 | // Uniqlo 34 | FashionStore uniqlo = new FashionStore("Uniqlo", new Person("Nate", "0199988776S")); 35 | uniqlo.addClothes("Shirt", 80); 36 | uniqlo.addClothes("T-shirt", 60); 37 | String[] uniqloEmployees = {"Kate", "Ken", "Kurt"}; 38 | uniqlo.addEmployee(uniqloEmployees); 39 | 40 | FashionStore padini = new FashionStore("Padini", new Person("Nick", "0195544332")); 41 | padini.addClothes("Blouse", 100); 42 | padini.addClothes("Skirt", 80); 43 | String[] padiniEmployees = {"Frank", "Felix"}; 44 | padini.addEmployee(padiniEmployees); 45 | 46 | FashionStore mango = new FashionStore("Mango", new Person("Nicole", "0194433221")); 47 | mango.addClothes("Dress", 120); 48 | String[] mangoEmployees = {"Ron", "John"}; 49 | mango.addEmployee(mangoEmployees); 50 | 51 | FashionStore[] fashionStores = {uniqlo, padini, mango}; 52 | 53 | //------------------- Testing ------------------- 54 | 55 | // 1 56 | System.out.println(sushiMentai + "\n"); 57 | System.out.println(mango + "\n"); 58 | 59 | // 2 60 | System.out.println("Food store with the highest number of employees: " + getHighestEmployees(foodStores)); 61 | System.out.println("Fashion store with the highest number of employees: " + getHighestEmployees(fashionStores)); 62 | System.out.println(); 63 | 64 | // 3 65 | String result = "different"; 66 | if (mcDonalds.equals(sushiMentai)) { 67 | result = "the same"; 68 | } 69 | System.out.println("The contact person for McDonalds and Sushi Mentai is " + result); 70 | 71 | result = "different"; 72 | if (mcDonalds.equals(waroengPenyet)) { 73 | result = "the same"; 74 | } 75 | System.out.println("The contact person for McDonalds and Waroeng Penyet is " + result); 76 | 77 | result = "different"; 78 | if (sushiMentai.equals(waroengPenyet)) { 79 | result = "the same"; 80 | } 81 | System.out.println("The contact person for Sushi Mentai and Waroeng Penyet is " + result); 82 | System.out.println(); 83 | 84 | // 4 85 | if (sushiMentai.compareTo(waroengPenyet) > 0) { 86 | System.out.println("Sushi Mentai have more employees than Waroeng Penyet"); 87 | } 88 | else if (sushiMentai.compareTo(waroengPenyet) < 0) { 89 | System.out.println("Waroeng Penyet have more employees than Sushi Mentai"); 90 | } 91 | else { 92 | System.out.println("Sushi Mentai have the same number of employees as Waroeng Penyet"); 93 | } 94 | System.out.println(); 95 | 96 | // 5 97 | System.out.println("The most expensive item in McDonalds is " + getMostExpensiveItem(mcDonalds)); 98 | System.out.println("The most expensive item in Padini is " + getMostExpensiveItem(padini)); 99 | } 100 | 101 | public static String getHighestEmployees(E[] shoplot) { 102 | int maxIndex = 0; 103 | int maxEmployees = 0; 104 | for (int i = 0; i < shoplot.length; i++) { 105 | int employees = shoplot[i].getNumOfEmployees(); 106 | if (employees > maxEmployees) { 107 | maxIndex = i; 108 | maxEmployees = employees; 109 | } 110 | } 111 | return shoplot[maxIndex].getName(); 112 | } 113 | 114 | public static String getMostExpensiveItem(E shoplot) { 115 | ArrayList items = shoplot.getItems(); 116 | int maxIndex = 0; 117 | int maxPrice = 0; 118 | for (int i = 0; i < items.size(); i++) { 119 | int price = items.get(i).getPrice(); 120 | if (price > maxPrice) { 121 | maxIndex = i; 122 | maxPrice = price; 123 | } 124 | } 125 | return items.get(maxIndex).getName(); 126 | } 127 | 128 | public static String findFoodStoreNameWithHighestEmployees(FoodStore[] foodStores) { 129 | FoodStore max = foodStores[0]; 130 | for (int i = 1; i < foodStores.length; i++) { 131 | if (foodStores[i].compareTo(max) > 0) { 132 | max = foodStores[i]; 133 | } 134 | } 135 | return max.getName(); 136 | } 137 | 138 | public static String findFashionStoreNameWithHighestEmployess(FashionStore[] fashionStores) { 139 | FashionStore max = fashionStores[0]; 140 | for (int i = 1; i < fashionStores.length; i++) { 141 | if (fashionStores[i].compareTo(max) > 0) { 142 | max = fashionStores[i]; 143 | } 144 | } 145 | return max.getName(); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /L04-Linked List/MyLinkedList.java: -------------------------------------------------------------------------------- 1 | public class MyLinkedList { 2 | Node head; 3 | Node tail; 4 | private int size; 5 | 6 | public MyLinkedList() { 7 | } 8 | 9 | public int getSize() { 10 | return size; 11 | } 12 | 13 | public void addFirst(E e) { 14 | Node temp = new Node<>(e); 15 | temp.next = head; 16 | head = temp; 17 | size++; 18 | if (tail == null) { 19 | tail = head; 20 | } 21 | } 22 | 23 | public void addLast(E e) { 24 | if (size == 0) { 25 | head = tail = new Node<>(e); 26 | } 27 | else { 28 | tail.next = new Node<>(e); 29 | tail = tail.next; 30 | } 31 | size++; 32 | } 33 | 34 | public void add(int index, E e) { 35 | if (index == 0) { 36 | addFirst(e); 37 | } 38 | else if (index >= size) { 39 | addLast(e); 40 | } 41 | else { 42 | Node current = head; 43 | for (int i = 1; i < index; i++) { 44 | current = current.next; 45 | } 46 | Node temp = current.next; 47 | current.next = new Node<>(e); 48 | (current.next).next = temp; 49 | size++; 50 | } 51 | } 52 | 53 | public E removeFirst() { 54 | if (size == 0) { 55 | return null; 56 | } 57 | else { 58 | Node temp = head; 59 | head = head.next; 60 | if (head == null) { 61 | tail = null; 62 | } 63 | size--; 64 | return temp.element; 65 | } 66 | } 67 | 68 | public E removeLast() { 69 | if (size == 0) { 70 | return null; 71 | } 72 | else if (size == 1) { 73 | Node temp = head; 74 | head = tail = null; 75 | size = 0; 76 | return temp.element; 77 | } 78 | else { 79 | Node current = head; 80 | for (int i = 1; i < size - 1; i++) { 81 | current = current.next; 82 | } 83 | Node temp = tail; 84 | tail = current; 85 | tail.next = null; 86 | size--; 87 | return temp.element; 88 | } 89 | } 90 | 91 | public E remove(int index) { 92 | if (index < 0 || index >= size) { 93 | return null; 94 | } 95 | else if (index == 0) { 96 | return removeFirst(); 97 | } 98 | else if (index == size - 1) { 99 | return removeLast(); 100 | } 101 | else { 102 | Node previous = head; 103 | for (int i = 1; i < index; i++) { 104 | previous = previous.next; 105 | } 106 | Node current = previous.next; 107 | previous.next = current.next; 108 | size--; 109 | return current.element; 110 | } 111 | } 112 | 113 | 114 | 115 | //Return nothing, but adds an element to the list 116 | public void add(E e) { 117 | addLast(e); 118 | } 119 | 120 | // Return true if list contains the element e 121 | public boolean contains(E e) { 122 | boolean found = false; 123 | Node current = head; 124 | while (!found && current != null) { 125 | if ((current.element).equals(e)) { 126 | found = true; 127 | } 128 | current = current.next; 129 | } 130 | return found; 131 | } 132 | 133 | // Return element at the specified index 134 | public E get(int index) { 135 | Node current = head; 136 | for (int i = 0; i < index; i++) { 137 | current = current.next; 138 | } 139 | return current.element; 140 | } 141 | 142 | // Return the value of the first item 143 | public E getFirst() { 144 | if (head == null) { 145 | return null; 146 | } 147 | return head.element; 148 | } 149 | 150 | // Return the value of the last item 151 | public E getLast() { 152 | if (tail == null) { 153 | return null; 154 | } 155 | return tail.element; 156 | } 157 | 158 | // Return the index of the head matching element in this list. 159 | // Return -1 of no match 160 | public int indexOf(E e) { 161 | int index = -1; 162 | Node current = head; 163 | if (current != null) { 164 | for (int i = 0; i < size; i++) { 165 | if ((current.element).equals(e)) { 166 | index = i; 167 | break; 168 | } 169 | current = current.next; 170 | } 171 | } 172 | return index; 173 | } 174 | 175 | // Return the index of the last matching element in this list. 176 | // Return -1 of no match 177 | public int lastIndexOf(E e) { 178 | int index = -1; 179 | Node current = head; 180 | if (current != null) { 181 | for (int i = 0; i < size; i++) { 182 | if (current.element.equals(e)) { 183 | index = i; 184 | } 185 | current = current.next; 186 | } 187 | } 188 | return index; 189 | } 190 | 191 | // Replace the element at the specified position in this list with the specified element 192 | public E set(int index, E e) { 193 | if (index < 0 || index >= size) { 194 | return null; 195 | } 196 | Node current = head; 197 | if (current == null) { 198 | return null; 199 | } 200 | for (int i = 0; i < index; i++) { 201 | current = current.next; 202 | } 203 | E temp = current.element; 204 | current.element = e; 205 | return temp; 206 | } 207 | 208 | // Clear the list 209 | public void clear() { 210 | while (size > 0) { 211 | removeLast(); 212 | } 213 | } 214 | 215 | // Print all the elements in the list 216 | public void print() { 217 | Node current = head; 218 | while (current != null) { 219 | System.out.print(current.element + " "); 220 | current = current.next; 221 | } 222 | System.out.println(); 223 | } 224 | 225 | // Print all elements in reverse order 226 | public void reverse() { 227 | Node current = head; 228 | Node last = null; 229 | while (last != head) { 230 | while (current.next != last) { 231 | current = current.next; 232 | } 233 | // store current element as new last 234 | last = current; 235 | System.out.print(last.element + " "); 236 | // reset current back to head 237 | current = head; 238 | } 239 | System.out.println(); 240 | } 241 | 242 | // Q2 243 | public E getMiddleValue() { 244 | int middle = size / 2; 245 | Node current = head; 246 | for (int i = 0; i < middle; i++) { 247 | current = current.next; 248 | } 249 | return current.element; 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /L11-Tree/BST.java: -------------------------------------------------------------------------------- 1 | public class BST> { 2 | TreeNode root; 3 | int size; 4 | 5 | public BST() { 6 | } 7 | 8 | /* Create a binary tree from an array of objects */ 9 | public BST(E[] objects) { 10 | for (int i = 0; i < objects.length; i++) 11 | insert(objects[i]); 12 | } 13 | 14 | /* Returns true if the element is in the tree */ 15 | public boolean search(E element) { 16 | TreeNode current = root; // Start from the root 17 | while (current != null) 18 | if (element.compareTo(current.element) < 0) { 19 | current = current.left; // Go left 20 | } 21 | else if (element.compareTo(current.element) > 0) { 22 | current = current.right; // Go right 23 | } 24 | else // Element matches current.element 25 | return true; // Element is found 26 | return false; // Element is not in the tree 27 | } 28 | 29 | /* Insert element o into the binary tree and return true if the element is inserted successfully */ 30 | public boolean insert(E element) { 31 | // Element inserted 32 | if (root == null) { 33 | root = new TreeNode<>(element); 34 | } 35 | else { 36 | // Locate the parent node 37 | TreeNode parent = root; 38 | TreeNode current = root; 39 | while (current != null) { 40 | if (element.compareTo(current.element) < 0) { 41 | parent = current; 42 | current = current.left; 43 | } else if (element.compareTo(current.element) > 0) { 44 | parent = current; 45 | current = current.right; 46 | } else { 47 | return false; // Duplicate node not inserted 48 | } 49 | } 50 | 51 | // Create the new node and attach it to the parent node 52 | if (element.compareTo(parent.element) < 0) { 53 | parent.left = new TreeNode<>(element); 54 | } 55 | else { 56 | parent.right = new TreeNode<>(element); 57 | } 58 | } 59 | size++; 60 | return true; 61 | } 62 | 63 | /* Get the number of nodes in the tree */ 64 | public int getSize() { 65 | return this.size; 66 | } 67 | 68 | /* Returns the height of the BST */ 69 | public int height() { 70 | return height(root); 71 | } 72 | 73 | private int height(TreeNode node) { 74 | if (node == null) { 75 | return -1; 76 | } 77 | else { 78 | int leftHeight = height(node.left); 79 | int rightHeight = height(node.right); 80 | 81 | if (leftHeight > rightHeight) { 82 | return leftHeight + 1; 83 | } 84 | else { 85 | return rightHeight + 1; 86 | } 87 | } 88 | } 89 | 90 | /* Returns the root of the BST */ 91 | public E getRoot() { 92 | return this.root.element; 93 | } 94 | 95 | /* Returns the minimum value of the BST */ 96 | public E minValue() { 97 | TreeNode parent = root; 98 | TreeNode current = root; 99 | 100 | while (current != null) { 101 | parent = current; 102 | current = current.left; 103 | } 104 | return parent.element; 105 | } 106 | 107 | /* Returns the maximum value of the BST */ 108 | public E maxValue() { 109 | TreeNode parent = root; 110 | TreeNode current = root; 111 | 112 | while (current != null) { 113 | parent = current; 114 | current = current.right; 115 | } 116 | return parent.element; 117 | } 118 | 119 | /* Returns a path from the root leading to the specified element */ 120 | public java.util.ArrayList> path(E e) { 121 | java.util.ArrayList> list = new java.util.ArrayList<>(); 122 | TreeNode current = root; 123 | 124 | while (current != null) { 125 | list.add(current); // Add the node to the list 126 | if (e.compareTo(current.element) < 0) { 127 | current = current.left; 128 | } 129 | else if (e.compareTo(current.element) > 0) { 130 | current = current.right; 131 | } 132 | else 133 | break; 134 | } 135 | return list; // Return an array list of nodes 136 | } 137 | 138 | /* Delete an element from the binary tree. Return true if the element is deleted 139 | successfully, and return false if the element is not in the tree */ 140 | public boolean delete(E e) { 141 | // Locate the node to be deleted and also locate its parent node 142 | TreeNode parent = null; 143 | TreeNode current = root; 144 | while (current != null) { 145 | if (e.compareTo(current.element) < 0) { 146 | parent = current; 147 | current = current.left; 148 | } 149 | else if (e.compareTo(current.element) > 0) { 150 | parent = current; 151 | current = current.right; 152 | } 153 | else 154 | break; // Element is in the tree pointed at by current 155 | } 156 | 157 | if (current == null) 158 | return false; // Element is not in the tree 159 | 160 | // Case 1: current has no left child 161 | if (current.left == null) { 162 | // Connect the parent with the right child of the current node 163 | if (parent == null) { 164 | root = current.right; 165 | } 166 | else { 167 | if (e.compareTo(parent.element) < 0) 168 | parent.left = current.right; 169 | else 170 | parent.right = current.right; 171 | } 172 | } 173 | else { 174 | // Case 2: The current node has a left child 175 | // Locate the rightmost node in the left subtree of 176 | // the current node and also its parent 177 | TreeNode parentOfRightMost = current; 178 | TreeNode rightMost = current.left; 179 | 180 | while (rightMost.right != null) { 181 | parentOfRightMost = rightMost; 182 | rightMost = rightMost.right; // Keep going to the right 183 | } 184 | 185 | // Replace the element in current by the element in rightMost 186 | current.element = rightMost.element; 187 | 188 | // Eliminate rightmost node 189 | if (parentOfRightMost.right == rightMost) 190 | parentOfRightMost.right = rightMost.left; 191 | else 192 | // Special case: parentOfRightMost == current 193 | parentOfRightMost.left = rightMost.left; 194 | } 195 | size--; 196 | return true; // Element deleted successfully 197 | } 198 | 199 | /* Remove all elements from the tree */ 200 | public boolean clear() { 201 | this.root = null; 202 | this.size = 0; 203 | return true; 204 | } 205 | 206 | public void inorder() { 207 | inorder(root); 208 | } 209 | 210 | public void postorder() { 211 | postorder(root); 212 | } 213 | 214 | public void preorder() { 215 | preorder(root); 216 | } 217 | 218 | /* Display inorder traversal from a subtree */ 219 | protected void inorder(TreeNode root) { 220 | if (root != null) { 221 | inorder(root.left); 222 | System.out.print(root.element + " "); 223 | inorder(root.right); 224 | } 225 | } 226 | 227 | /* Display postorder traversal from a subtree */ 228 | protected void postorder(TreeNode root) { 229 | if (root != null) { 230 | postorder(root.left); 231 | postorder(root.right); 232 | System.out.print(root.element + " "); 233 | } 234 | } 235 | 236 | /* Display preorder traversal from a subtree */ 237 | protected void preorder(TreeNode root) { 238 | if (root != null) { 239 | System.out.print(root.element + " "); 240 | preorder(root.left); 241 | preorder(root.right); 242 | } 243 | } 244 | 245 | } 246 | -------------------------------------------------------------------------------- /L08-Graph/WeightedGraph.java: -------------------------------------------------------------------------------- 1 | package Lab.L8; 2 | 3 | import java.util.ArrayList; 4 | 5 | class WeightedGraph, N extends Comparable> { 6 | Vertex head; 7 | int size; 8 | 9 | public WeightedGraph() { 10 | this.head = null; 11 | this.size = 0; 12 | } 13 | 14 | public int getSize() { 15 | return size; 16 | } 17 | 18 | public boolean hasVertex(T vertexInfo) { 19 | if (head == null) { 20 | return false; 21 | } 22 | Vertex current = head; 23 | while (current != null) { 24 | if (current.vertexInfo.compareTo(vertexInfo) == 0) { 25 | return true; 26 | } 27 | current = current.nextVertex; 28 | } 29 | return false; 30 | } 31 | 32 | public int getIndeg(T vertexInfo) { 33 | if (hasVertex(vertexInfo)) { 34 | Vertex current = head; 35 | while (current != null) { 36 | if (current.vertexInfo.compareTo(vertexInfo) == 0) { 37 | return current.indeg; 38 | } 39 | current = current.nextVertex; 40 | } 41 | } 42 | return -1; 43 | } 44 | 45 | public int getOutdeg(T vertexInfo) { 46 | if (hasVertex(vertexInfo)) { 47 | Vertex current = head; 48 | while (current != null) { 49 | if (current.vertexInfo.compareTo(vertexInfo) == 0) { 50 | return current.outdeg; 51 | } 52 | current = current.nextVertex; 53 | } 54 | } 55 | return -1; 56 | } 57 | 58 | public boolean addVertex(T vertexInfo) { 59 | if (hasVertex(vertexInfo)) { 60 | return false; 61 | } 62 | Vertex current = head; 63 | Vertex newVertex = new Vertex<>(vertexInfo, null); 64 | if (current == null) { 65 | head = newVertex; 66 | } 67 | else { 68 | while (current.nextVertex != null) { 69 | current = current.nextVertex; 70 | } 71 | current.nextVertex = newVertex; 72 | } 73 | size++; 74 | return true; 75 | } 76 | 77 | public int getIndex(T vertexInfo) { 78 | Vertex current = head; 79 | for (int i = 0; i < size; i++) { 80 | if (current.vertexInfo.compareTo(vertexInfo) == 0) { 81 | return i; 82 | } 83 | current = current.nextVertex; 84 | } 85 | return -1; 86 | } 87 | 88 | public ArrayList getAllVertexObjects() { 89 | ArrayList list = new ArrayList<>(); 90 | Vertex current = head; 91 | while (current != null) { 92 | list.add(current.vertexInfo); 93 | current = current.nextVertex; 94 | } 95 | return list; 96 | } 97 | 98 | public T getVertex(int index) { 99 | if (index >= size || index < 0) { 100 | return null; 101 | } 102 | Vertex current = head; 103 | for (int i = 0; i < index; i++) { 104 | current = current.nextVertex; 105 | } 106 | return current.vertexInfo; 107 | } 108 | 109 | public boolean hasEdge(T source, T destination) { 110 | if (head == null) { 111 | return false; 112 | } 113 | if (!hasVertex(source) || !hasVertex(destination)) { 114 | return false; 115 | } 116 | 117 | Vertex sourceVertex = head; 118 | while (sourceVertex != null) { 119 | if (sourceVertex.vertexInfo.compareTo(source) == 0) { 120 | 121 | Edge currentEdge = sourceVertex.firstEdge; 122 | while (currentEdge != null) { 123 | if (currentEdge.toVertex.vertexInfo.compareTo(destination) == 0) { 124 | return true; 125 | } 126 | currentEdge = currentEdge.nextEdge; 127 | } 128 | } 129 | sourceVertex = sourceVertex.nextVertex; 130 | } 131 | return false; 132 | } 133 | 134 | public boolean addEdge(T source, T destination, N weight) { 135 | if (head == null) { 136 | return false; 137 | } 138 | if (!hasVertex(source) || !hasVertex(destination)) { 139 | return false; 140 | } 141 | 142 | Vertex sourceVertex = head; 143 | while (sourceVertex != null) { 144 | if (sourceVertex.vertexInfo.compareTo(source) == 0) { 145 | 146 | Vertex destinationVertex = head; 147 | while (destinationVertex != null) { 148 | if (destinationVertex.vertexInfo.compareTo(destination) == 0) { 149 | Edge currentEdge = sourceVertex.firstEdge; 150 | Edge newEdge = new Edge<>(destinationVertex, weight, currentEdge); 151 | sourceVertex.firstEdge = newEdge; 152 | 153 | sourceVertex.outdeg++; 154 | destinationVertex.indeg++; 155 | return true; 156 | } 157 | destinationVertex = destinationVertex.nextVertex; 158 | } 159 | } 160 | sourceVertex = sourceVertex.nextVertex; 161 | } 162 | return false; 163 | } 164 | 165 | public N getEdgeWeight(T source, T destination) { 166 | if (head == null) { 167 | return null; 168 | } 169 | if (!hasVertex(source) || !hasVertex(destination)) { 170 | return null; 171 | } 172 | 173 | Vertex sourceVertex = head; 174 | while (sourceVertex != null) { 175 | if (sourceVertex.vertexInfo.compareTo(source) == 0) { 176 | Edge currentEdge = sourceVertex.firstEdge; 177 | while (currentEdge != null) { 178 | if (currentEdge.toVertex.vertexInfo.compareTo(destination) == 0) { 179 | return currentEdge.weight; 180 | } 181 | currentEdge = currentEdge.nextEdge; 182 | } 183 | } 184 | sourceVertex = sourceVertex.nextVertex; 185 | } 186 | return null; 187 | } 188 | 189 | public ArrayList getNeighbours(T vertex) { 190 | if (!hasVertex(vertex)) { 191 | return null; 192 | } 193 | ArrayList list = new ArrayList<>(); 194 | Vertex current = head; 195 | while (current != null) { 196 | if (current.vertexInfo.compareTo(vertex) == 0) { 197 | Edge currentEdge = current.firstEdge; 198 | while (currentEdge != null) { 199 | list.add(currentEdge.toVertex.vertexInfo); 200 | currentEdge = currentEdge.nextEdge; 201 | } 202 | } 203 | current = current.nextVertex; 204 | } 205 | return list; 206 | } 207 | 208 | public void printEdges() { 209 | Vertex current = head; 210 | while (current != null) { 211 | System.out.printf("# %s : ", current.vertexInfo); 212 | Edge currentEdge = current.firstEdge; 213 | while (currentEdge != null) { 214 | System.out.printf("[%s, %s] ", current.vertexInfo, currentEdge.toVertex.vertexInfo); 215 | currentEdge = currentEdge.nextEdge; 216 | } 217 | System.out.println(); 218 | current = current.nextVertex; 219 | } 220 | } 221 | 222 | // Q1 223 | public boolean addUndirectedEdge(T source, T destination, N weight) { 224 | return (addEdge(source, destination, weight) && addEdge(destination, source, weight)); 225 | } 226 | 227 | // Q2 228 | public Edge removeEdge(T source, T destination) { 229 | if (head == null) { 230 | return null; 231 | } 232 | if (!hasVertex(source) || !hasVertex(destination)) { 233 | return null; 234 | } 235 | 236 | Vertex currentSource = head; 237 | while (currentSource != null) { 238 | if (currentSource.vertexInfo.compareTo(source) == 0) { 239 | Edge previousEdge = currentSource.firstEdge; 240 | Edge currentEdge = currentSource.firstEdge; 241 | while (currentEdge != null) { 242 | if (currentEdge.toVertex.vertexInfo.compareTo(destination) == 0) { 243 | previousEdge.nextEdge = currentEdge.nextEdge; 244 | currentEdge.nextEdge = null; 245 | currentSource.outdeg--; 246 | currentEdge.toVertex.indeg--; 247 | currentEdge.toVertex = null; 248 | size--; 249 | return currentEdge; 250 | } 251 | previousEdge = currentEdge; 252 | currentEdge = currentEdge.nextEdge; 253 | } 254 | } 255 | currentSource = currentSource.nextVertex; 256 | } 257 | return null; 258 | } 259 | 260 | } 261 | --------------------------------------------------------------------------------