From 5ef405a98be7b59087ac2c15318116e426f9c035 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Mon, 25 Aug 2025 13:17:20 -0500 Subject: [PATCH 01/29] day 1 of linedlist notes finished with iterator.next() --- Chapter 15 Class Notes/src/ListDemo.java | 25 ++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/Chapter 15 Class Notes/src/ListDemo.java b/Chapter 15 Class Notes/src/ListDemo.java index b6f9afc08..4d3fab9dc 100644 --- a/Chapter 15 Class Notes/src/ListDemo.java +++ b/Chapter 15 Class Notes/src/ListDemo.java @@ -9,6 +9,27 @@ public class ListDemo { public static void main(String[] args) { - - } + /* the addLast method can be used to populate a list */ + LinkedList staff = new LinkedList<>(); + staff.addLast("Tony"); + staff.addLast("Natasha"); + staff.addLast("Peter"); + staff.addLast("Steve"); + + System.out.println(staff); + + //The list is currently: TNPS + + /* + * The listIterator method creates a new list iterator that is positioned at the head of the list. + * The | is used to represent the iterator position + */ + ListIterator iterator = staff.listIterator(); // |TNPS iterator is right before the linkedlist + + /* The next method advances the iterator OVER the next element in the list. */ + iterator.next(); // T| NPS + /* The next method also returns the element that the iterator passes over. */ + String avenger = iterator.next(); + System.out.println(avenger); //should print natasha + } } From cdb256b00f022bd870255beaa0201b4b2fad81e7 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Tue, 26 Aug 2025 13:16:29 -0500 Subject: [PATCH 02/29] new notes abt iteration --- Chapter 15 Class Notes/src/ListDemo.java | 58 ++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/Chapter 15 Class Notes/src/ListDemo.java b/Chapter 15 Class Notes/src/ListDemo.java index 4d3fab9dc..24532ed1c 100644 --- a/Chapter 15 Class Notes/src/ListDemo.java +++ b/Chapter 15 Class Notes/src/ListDemo.java @@ -30,6 +30,64 @@ public static void main(String[] args) iterator.next(); // T| NPS /* The next method also returns the element that the iterator passes over. */ String avenger = iterator.next(); + // TN|PS System.out.println(avenger); //should print natasha + + /* The add method inserts an element at the iterator position. + * The iterator is then positioned AFTER the element that was added + */ + iterator.add("Clint"); //TNC|PS + iterator.add("Bruce"); //TNCB|PS + System.out.println(staff); + /* The remove method can ONLY be called after calling next or previous */ + // iterator.remove(); This line would cause an IllegalStateException error + //The remove method removes the element returned after calling next or previous (removes the one right before the next) + iterator.next(); + iterator.remove(); //Peter is removed -> TNCB|S + System.out.println(staff); + + /* + * The set method updates the element returned by the last call to next or previous + */ + iterator.previous(); //TNC|BS + iterator.set("Thor"); //Bruce is replaced by Thor TNC|TS + //passed over Bruce when previous was called to bruce was replaced by thor + System.out.println(staff); + + /* The hasNext method is used to deterine if there is a next node after the iterator (make sure ur not at the end of the list). The hasNext method is often used + * in the condition of a while loop + */ + iterator = staff.listIterator(); //|TNCTS + while (iterator.hasNext()) { + String n = iterator.next(); + if (n.equals("Natasha")){ //TN|CTS + iterator.remove(); //T|CTS + } + } //TCST| + /*Enhanced for loop works with linkedlist as well */ + for (String n: staff){ + System.out.println(n+" "); + } + System.out.println(); + + /*ConcurrentModificationException + * CANNOT modify a linkedlist while using an iterator + * UNLESS you use the iterator to do the modification + */ + iterator = staff.listIterator(); //|TCTS + while(iterator.hasNext()){ + String n = iterator.next(); + if (n.equals("Tony")){ + //staff.remove(); ConcurrentModificationException + } + } + //automatic iterator in the background already in the for each loop like the one below + for (String n: staff){ + if (n.equals("Tony")){ + staff.add("T'Challa"); + } + } + System.out.println(staff); + } } From a350fda53b55eb2055bb751da95f7212696849a8 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Thu, 28 Aug 2025 13:29:49 -0500 Subject: [PATCH 03/29] reverse --- Chapter 15 Activities/Reverse/src/ListUtil.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Chapter 15 Activities/Reverse/src/ListUtil.java b/Chapter 15 Activities/Reverse/src/ListUtil.java index d3e8e9f83..478ca1141 100644 --- a/Chapter 15 Activities/Reverse/src/ListUtil.java +++ b/Chapter 15 Activities/Reverse/src/ListUtil.java @@ -1,4 +1,5 @@ import java.util.LinkedList; +import java.util.ListIterator; /** * This class supplies a utility method to reverse the entries in a linked list. @@ -12,6 +13,18 @@ public class ListUtil */ public static void reverse(LinkedList strings) { - ... + ListIterator iterator = strings.listIterator(); + String end =""; + iterator.next(); + while(iterator.hasNext()){ + // iterator.next(); + end = strings.getFirst(); + iterator.next(); + strings.add(end); + //String temp = iterator.next(); + } + /* get last add and then add to teh current position with the iterator remove the previoous and move on to the next keep + * array list + */ } } \ No newline at end of file From f001246cfa9666e6041299a0a211dc6268492aba Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Fri, 29 Aug 2025 13:13:27 -0500 Subject: [PATCH 04/29] final reverse program done --- .../Reverse/src/ListUtil.java | 27 ++++++++++++------- .../Reverse/src/ReverseTester.java | 2 ++ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/Chapter 15 Activities/Reverse/src/ListUtil.java b/Chapter 15 Activities/Reverse/src/ListUtil.java index 478ca1141..ac43b98ac 100644 --- a/Chapter 15 Activities/Reverse/src/ListUtil.java +++ b/Chapter 15 Activities/Reverse/src/ListUtil.java @@ -1,3 +1,11 @@ +/* + * Shriya Kunnanath + * 8/29/2025 + * Software Engineering 1 + * Reverse List Program + */ + +import java.util.ArrayList; import java.util.LinkedList; import java.util.ListIterator; @@ -13,18 +21,19 @@ public class ListUtil */ public static void reverse(LinkedList strings) { + //made a list iterator and arraylist to set up the reversed list and an iterator to go through the linkedlist ListIterator iterator = strings.listIterator(); - String end =""; - iterator.next(); + ArrayList tempList = new ArrayList<>(); + + //the while loop goes through the list while(iterator.hasNext()){ - // iterator.next(); - end = strings.getFirst(); iterator.next(); - strings.add(end); - //String temp = iterator.next(); + + //the first value is added to templist and then removed from the original linkedlist + tempList.add(0, strings.getFirst()); + iterator.remove(); } - /* get last add and then add to teh current position with the iterator remove the previoous and move on to the next keep - * array list - */ + //all the content from tempList is transfered into the empty strings linkedlist + strings.addAll(tempList); } } \ No newline at end of file diff --git a/Chapter 15 Activities/Reverse/src/ReverseTester.java b/Chapter 15 Activities/Reverse/src/ReverseTester.java index 0a710b1aa..0b1c8b45a 100644 --- a/Chapter 15 Activities/Reverse/src/ReverseTester.java +++ b/Chapter 15 Activities/Reverse/src/ReverseTester.java @@ -1,4 +1,6 @@ +import java.util.ArrayList; import java.util.LinkedList; +import java.util.ListIterator; /** From 89b85d343d3d23c4ec3910baefc819c6a613efce Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Thu, 4 Sep 2025 13:28:55 -0500 Subject: [PATCH 05/29] word analyis --- Chapter 15 Class Notes/src/WordAnalysis.java | 39 +++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/Chapter 15 Class Notes/src/WordAnalysis.java b/Chapter 15 Class Notes/src/WordAnalysis.java index ffe5bc7af..ea97e1da6 100644 --- a/Chapter 15 Class Notes/src/WordAnalysis.java +++ b/Chapter 15 Class Notes/src/WordAnalysis.java @@ -13,6 +13,33 @@ public class WordAnalysis public static void main(String[] args) throws FileNotFoundException { + //Determine the current working directory + System.out.println(System.getProperty("user.dir")); + + //Read the dictionary file and the novel file + //Chapter 15 Class Notes/src/ + Set dictionaryWords = readWords("data-structures/Chapter 15 Class Notes/src/words"); + Set novelWords = readWords("data-structures\\Chapter 15 Class Notes\\src\\war-and-peace.txt"); + + //print all the words that are in the novel, but not the dictionary + for (String words: novelWords){ + if (!dictionaryWords.contains(words)){ + System.out.println(words); + } + } + + //print out the number of unique words in the novel + System.out.println("There are "+novelWords.size()+" unique words in the novel"); + + //Print the number of unique words with >3 letters + Iterator iterator = novelWords.iterator(); + while (iterator.hasNext()){ + if(iterator.next().length() <=3){ + iterator.remove(); + } + } + + System.out.println("There are "+novelWords.size()+" unique words with more than 3 letters"); } /** @@ -25,6 +52,16 @@ public static void main(String[] args) public static Set readWords(String filename) throws FileNotFoundException { - return null; + //we use a HashSet instead of a TreeSet because the order doens't matter + Set words = new HashSet<>(); + Scanner in = new Scanner(new File(filename), "UTF-8"); + //Use any character that's not a letter as a delimiter + in.useDelimiter("[^a-zA-Z]+"); + while(in.hasNext()){ + //add words to the set (duplicates are automatically ignored) + words.add(in.next().toLowerCase()); + + } + return words; } } From 89b1e1581eddf789188874b5caff0089e2122b90 Mon Sep 17 00:00:00 2001 From: shriya Date: Tue, 9 Sep 2025 00:23:15 -0500 Subject: [PATCH 06/29] sieve --- Chapter 15 Activities/Sieve/src/Sieve.java | 31 +++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/Chapter 15 Activities/Sieve/src/Sieve.java b/Chapter 15 Activities/Sieve/src/Sieve.java index 297f5da6a..7c809e2d2 100644 --- a/Chapter 15 Activities/Sieve/src/Sieve.java +++ b/Chapter 15 Activities/Sieve/src/Sieve.java @@ -1,7 +1,12 @@ +import java.util.ArrayList; +import java.util.HashSet; import java.util.Scanner; +import java.util.Set; /** + * Shriya Kunnanath + * 9/8/25 * A program that implements the sieve of Eratosthenes. */ public class Sieve @@ -11,15 +16,35 @@ public static void main(String[] args) Scanner in = new Scanner(System.in); System.out.println("Compute primes up to which integer?"); int n = in.nextInt(); + - // Your work goes here - . . . - + Set prime = new HashSet<>(); + for (int i=2; i<= n; i++){ + prime.add(i); + } + //made an arraylist that has the numbers in the range from the original value of n + ArrayList numbers = new ArrayList<>(prime); + // Loop through numbers starting from 2 up to the square root of n + for (int i = 2; i * i <= n; i++) { + // Only proceed if 'i' is still in the set + if (prime.contains(i)) { + // Loop through all multiples of 'i' starting from i*2 up to n + for (int j = i * 2; j <= n; j += i) { + // Remove 'j' from the set since it's a multiple of 'i' and not a prime + prime.remove(j); + } + } +} + //print prime numbers + numbers = new ArrayList<>(prime); + numbers.sort(null); // sort the list + System.out.println(numbers); + System.out.println(prime); } } From 043715167354f999289ef4e61a00da1103a13151 Mon Sep 17 00:00:00 2001 From: shriya Date: Tue, 9 Sep 2025 23:45:38 -0500 Subject: [PATCH 07/29] notess --- .../Sudoku/src/SudokuSolver.java | 140 +++++++++++++++--- Chapter 15 Class Notes/src/MapDemo.java | 27 +++- 2 files changed, 147 insertions(+), 20 deletions(-) diff --git a/Chapter 15 Activities/Sudoku/src/SudokuSolver.java b/Chapter 15 Activities/Sudoku/src/SudokuSolver.java index b24090a24..58b3c5402 100644 --- a/Chapter 15 Activities/Sudoku/src/SudokuSolver.java +++ b/Chapter 15 Activities/Sudoku/src/SudokuSolver.java @@ -13,6 +13,8 @@ public class SudokuSolver { public SudokuSolver(String fileName) { // read the puzzle file + System.out.println(System.getProperty("user.dir")); + try (Scanner in = new Scanner(new File(fileName))) { this.grid = new int[N][N]; @@ -35,11 +37,64 @@ public SudokuSolver(String fileName) { System.out.println("Cannot open: " + fileName); } + Set losRow = new HashSet<>(); + this.rows = new ArrayList<>(); + //losRow.size[N]; + //System.out.println(grid); // create the list of sets for each row (this.rows) + for (int i = 0; i < N; i++) { + losRow = new HashSet<>(); + //put each row in a set and then put it in a list. + for (int j = 0; j < N; j++) { + losRow.add(this.grid[i][j]); + + //System.out.print(losRow); + //rows.add(losRow); + //System.out.println(); + } + this.rows.add(losRow); + //System.out.println(losRow); + + //losRow = new HashSet<>(); + + + + //System.out.println(rows); + + + } + // ... // create the list of sets for each col (this.cols) // ... + //Set losCol = new HashSet<>(); + this.cols = new ArrayList<>(); + + for (int j = 0; j < N; j++) { + //put each row in a set and then put it in a list. + Set losCol = new HashSet<>(); + for (int i = 0; i < N; i++) { + + losCol.add(this.grid[i][j]); + + //System.out.print(losCol); + //rows.add(losRow); + //System.out.println(); + } + this.cols.add(losCol); + //System.out.println(losCol); + + //losCol = new HashSet<>(); + + + + //System.out.println(rows); + + + } + + // create the list of sets for each square (this.squares) /* the squares are added to the list row-by-row: @@ -49,9 +104,42 @@ public SudokuSolver(String fileName) { */ // ... + //Set SquareRow = new HashSet<>(); + + this.squares = new ArrayList<>(); + for (int squareRow = 0; squareRow < M; squareRow++) { + for (int squareCol = 0; squareCol < M; squareCol++) { + Set squareSet = new HashSet<>(); + for (int row = squareRow * M; row < (squareRow + 1) * M; row++) { + for (int col = squareCol * M; col < (squareCol + 1) * M; col++) { + if (this.grid[row][col] != 0) { + squareSet.add(this.grid[row][col]); + } + } + } + this.squares.add(squareSet); + } +} + + + + //System.out.println(rows); + + + + + + + // create a hash set for [1..9] (this.nums) // ... + this.nums = new HashSet<>(); + for (int i = 1; i <= N; i++) { + this.nums.add(i); + } + + // visually inspect that all the sets are correct for (int row = 0; row < N; row++) { System.out.println("row " + row + ": " + this.rows.get(row)); @@ -96,7 +184,17 @@ corresponding to nextRow, nextCol, and the corresponding square (use the */ Set possibleNums = new HashSet(); possibleNums.addAll(this.nums); - + + //remove nums alr in row + possibleNums.removeAll(this.rows.get(nextRow)); + + // remove nums already in the column + possibleNums.removeAll(this.cols.get(nextCol)); + + // calculate square index and remove numbers alr in square + int squareIndex = (nextRow / M) * M + (nextCol / M); + possibleNums.removeAll(this.squares.get(squareIndex)); + // ... // if there are no possible numbers, we cannot solve the board in its current state @@ -106,22 +204,26 @@ corresponding to nextRow, nextCol, and the corresponding square (use the // try each possible number for (Integer possibleNum : possibleNums) { - // update the grid and all three corresponding sets with possibleNum - // ... - - // recursively solve the board - if (this.solve()) { - // the board is solved! - return true; - } else { - /* - Undo the move before trying another possible number by setting the corresponding - element in the grid back to 0 and removing possibleNum from all three corresponding - sets. - */ - // ... - } - } + // Update the grid and all three corresponding sets with possibleNum + this.grid[nextRow][nextCol] = possibleNum; + this.rows.get(nextRow).add(possibleNum); + this.cols.get(nextCol).add(possibleNum); + //int squareIndex = (nextRow / M) * M + (nextCol / M); + this.squares.get(squareIndex).add(possibleNum); + + // Recursively solve the board + if (this.solve()) { + // The board is solved! + return true; + } else { + // Undo the move before trying another possible number + this.grid[nextRow][nextCol] = 0; + this.rows.get(nextRow).remove(possibleNum); + this.cols.get(nextCol).remove(possibleNum); + this.squares.get(squareIndex).remove(possibleNum); + } +} + return false; } @@ -141,8 +243,8 @@ public String toString() { } public static void main(String[] args) { - String fileName = "src/puzzle1.txt"; - + String fileName = "Chapter 15 Activities/Sudoku/src/puzzle1.txt"; + //String fileName = "data-structures/Chapter 15 Activities/Sudoku/src/puzzle1.txt"; //PERSONAL HOME USE SudokuSolver solver = new SudokuSolver(fileName); System.out.println(solver); if (solver.solve()) { diff --git a/Chapter 15 Class Notes/src/MapDemo.java b/Chapter 15 Class Notes/src/MapDemo.java index 835c1ba27..758192a0c 100644 --- a/Chapter 15 Class Notes/src/MapDemo.java +++ b/Chapter 15 Class Notes/src/MapDemo.java @@ -11,5 +11,30 @@ public class MapDemo { public static void main(String[] args) { + /* The Map interface is generic. + * The first type given is the key. + * The second type given is the value. + */ + Map favColors = new HashMap<>(); + + // Add elements to the map using the put method + favColors.put("Sreeram", Color.GREEN); + favColors.put("Cam", Color.BLUE); + favColors.put("Nimai", Color.RED); + + // Two different elements with the same value + favColors.put("Kaitlyn", Color.GREEN); + + // The same key CANNOT have two different values + // Using put on a key that exists, changes the value + favColors.put("Cam", Color.ORANGE); + + // Create a set of the keys in a map + Set keys = favColors.keySet(); + for (String key: keys) { + // [name] ([hasCode]): [color] + System.out.println(key + "("+key.hashCode()+"): "+favColors.get(key)); + } + } -} +} \ No newline at end of file From d01521311607398faf806c8528ff1e2cbfbcb96c Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Fri, 12 Sep 2025 12:30:23 -0500 Subject: [PATCH 08/29] Update Gradebook.java --- .../Gradebook/src/Gradebook.java | 41 +++++++++++++++---- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/Chapter 15 Activities/Gradebook/src/Gradebook.java b/Chapter 15 Activities/Gradebook/src/Gradebook.java index 3e4b59f92..a9c87ca87 100644 --- a/Chapter 15 Activities/Gradebook/src/Gradebook.java +++ b/Chapter 15 Activities/Gradebook/src/Gradebook.java @@ -1,5 +1,8 @@ +import java.util.HashMap; +import java.util.Map; import java.util.Scanner; -. . . +import java.util.Set; + /** * A program to add, remove, modify or print * student names and grades. @@ -10,33 +13,53 @@ public static void main(String[] args) { Scanner in = new Scanner(System.in); - . . . + Map gradebook = new HashMap<>(); + //Set keys = gradebook.keySet(); + boolean done = false; while(!done) { System.out.println("A)dd R)emove M)odify P)rint Q)uit"); + String input = in.next().toUpperCase(); if (input.equals("Q")) { done = true; } else if (input.equals("A")) { - . . . + String name = in.next(); + String grade = in.next(); + gradebook.put(name, grade); } else if (input.equals("R")) { - . . . - } else if (input.equals("M")) + String name = in.next(); + + Set keys = gradebook.keySet(); + for (String key: keys) { + if (key==name){ + gradebook.remove(key);} + }}else if (input.equals("M")) { - . . . - } else if (input.equalsIgnoreCase("P")) + String name = in.next(); + String grade = in.next(); + + Set list=gradebook.keySet(); + for (String key: list){ + if (key.equals(name)){ + gradebook.put(name, grade); + + }else if (input.equalsIgnoreCase("P")) { - . . . + Set x = gradebook.keySet(); + for (String i: x) { + System.out.println(i + ": "+gradebook.get(i)); + } } else { done = true; } } } -} + }}} From 636cb1107f3db88535ebaf15301fa5c8d0399387 Mon Sep 17 00:00:00 2001 From: shriya Date: Sun, 14 Sep 2025 17:05:00 -0500 Subject: [PATCH 09/29] gradebook --- .../Gradebook/src/Gradebook.java | 85 ++++++++++--------- 1 file changed, 45 insertions(+), 40 deletions(-) diff --git a/Chapter 15 Activities/Gradebook/src/Gradebook.java b/Chapter 15 Activities/Gradebook/src/Gradebook.java index a9c87ca87..738a14ca2 100644 --- a/Chapter 15 Activities/Gradebook/src/Gradebook.java +++ b/Chapter 15 Activities/Gradebook/src/Gradebook.java @@ -1,65 +1,70 @@ + +/** + * Shriya Kunnanath + * 9/14/25 + * gradebook program +*/ +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; -/** - * A program to add, remove, modify or print - * student names and grades. -*/ -public class Gradebook -{ - public static void main(String[] args) - { +public class Gradebook { + public static void main(String[] args) { + // Create scanner and gradebook map Scanner in = new Scanner(System.in); - Map gradebook = new HashMap<>(); - //Set keys = gradebook.keySet(); - + // Loop until user chooses to quit boolean done = false; - while(!done) - { + + while (!done) { + // Prompt for user action System.out.println("A)dd R)emove M)odify P)rint Q)uit"); - String input = in.next().toUpperCase(); - if (input.equals("Q")) - { + + // Quit the program + if (input.equals("Q")) { done = true; - } else if (input.equals("A")) - { + + // Add a student and their grade + } else if (input.equals("A")) { String name = in.next(); String grade = in.next(); gradebook.put(name, grade); - } else if (input.equals("R")) - { + // Remove a student + } else if (input.equals("R")) { String name = in.next(); + if (gradebook.containsKey(name)) { + gradebook.remove(name); + } - Set keys = gradebook.keySet(); - for (String key: keys) { - if (key==name){ - gradebook.remove(key);} - }}else if (input.equals("M")) - { + // Modify a student's grade + } else if (input.equals("M")) { String name = in.next(); - String grade = in.next(); + if (gradebook.containsKey(name)) { + String grade = in.next(); + gradebook.put(name, grade); + } - Set list=gradebook.keySet(); - for (String key: list){ - if (key.equals(name)){ - gradebook.put(name, grade); + // Print all students and grades in alphabetical order + } else if (input.equals("P")) { + System.out.println(); + List names = new ArrayList<>(gradebook.keySet()); + Collections.sort(names); - }else if (input.equalsIgnoreCase("P")) - { - Set x = gradebook.keySet(); - for (String i: x) { - System.out.println(i + ": "+gradebook.get(i)); - } - } else - { + for (String name : names) { + System.out.println(name + ": " + gradebook.get(name)); + } + System.out.println(); + + } else { done = true; } } } - }}} +} From f928942c50fb2b497fe66990aa37fb994ed93340 Mon Sep 17 00:00:00 2001 From: shriya Date: Sun, 14 Sep 2025 19:34:42 -0500 Subject: [PATCH 10/29] code done --- .vscode/launch.json | 77 +++++++++++++++++++ .../Downsize/src/Business.java | 2 +- .../FirstLetterMap1/src/FirstLetterMap.java | 21 +++-- .../FirstLetterMap2/src/FirstLetterMap.java | 36 ++++++--- .../StringLengthMap/src/StringLengthMap.java | 26 ++++--- .../StringLengthMap/src/StringLengthMap2.java | 13 +++- 6 files changed, 143 insertions(+), 32 deletions(-) create mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..5beffa6a5 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,77 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "java", + "name": "Current File", + "request": "launch", + "mainClass": "${file}" + }, + { + "type": "java", + "name": "FirstLetterMap", + "request": "launch", + "mainClass": "FirstLetterMap", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "Gradebook", + "request": "launch", + "mainClass": "Gradebook", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "ListDemo", + "request": "launch", + "mainClass": "ListDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "MapDemo", + "request": "launch", + "mainClass": "MapDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "PriorityQueueDemo", + "request": "launch", + "mainClass": "PriorityQueueDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "QueueDemo", + "request": "launch", + "mainClass": "QueueDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "StackDemo", + "request": "launch", + "mainClass": "StackDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "SudokuSolver", + "request": "launch", + "mainClass": "SudokuSolver", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "WordAnalysis", + "request": "launch", + "mainClass": "WordAnalysis", + "projectName": "data-structures_addf3fee" + } + ] +} \ No newline at end of file diff --git a/Chapter 15 Activities/Downsize/src/Business.java b/Chapter 15 Activities/Downsize/src/Business.java index 0769e2634..6f64de50e 100644 --- a/Chapter 15 Activities/Downsize/src/Business.java +++ b/Chapter 15 Activities/Downsize/src/Business.java @@ -13,6 +13,6 @@ public class Business */ public static void downsize(LinkedList employeeNames, int n) { - ... + } } diff --git a/Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/FirstLetterMap.java b/Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/FirstLetterMap.java index 826e6eb93..a693f8434 100644 --- a/Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/FirstLetterMap.java +++ b/Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/FirstLetterMap.java @@ -12,13 +12,12 @@ public class FirstLetterMap { public static void main(String[] args) { - String filename = "src/test1.txt"; + String filename = "Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/test1.txt"; try (Scanner in = new Scanner(new File(filename))) { - // Create your map here - ... + Map> firstLetterMap = new TreeMap<>(); while (in.hasNext()) { @@ -27,13 +26,23 @@ public static void main(String[] args) // Update the map here // Use the Java 8 merge method - . . . + if (word.length() > 0) { + + // Use the Java 8 merge method to update the map + firstLetterMap.merge(c, new TreeSet<>(Set.of(word)), (existingSet, newSet) -> { + existingSet.addAll(newSet); + return existingSet; + }); + } } // Print the map here in this form // a: [a, able, aardvark] - . . . + + for (Map.Entry> entry : firstLetterMap.entrySet()) { + System.out.println(entry.getKey() + ": " + entry.getValue()); + } } catch (FileNotFoundException e) { System.out.println("Cannot open: " + filename); @@ -53,5 +62,5 @@ public static String clean(String s) } return r.toLowerCase(); } - + //in.close(); } diff --git a/Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/FirstLetterMap.java b/Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/FirstLetterMap.java index d1e2075e4..486de0a2f 100644 --- a/Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/FirstLetterMap.java +++ b/Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/FirstLetterMap.java @@ -4,21 +4,20 @@ * Read all words from a file and add them to a map * whose keys are the first letters of the words and * whose values are sets of words that start with - * that same letter. Then print out the word sets in - * alphabetical order. Update the map by modifying - * Worked Example 15.1. + * that same letter. + * Then print out the word sets in alphabetical order. + * Use the Java 8 merge() feature. */ public class FirstLetterMap { public static void main(String[] args) { - String filename = "src/test1.txt"; + String filename = "Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/test1.txt"; try (Scanner in = new Scanner(new File(filename))) { - // Create your map here - ... + Map> firstLetterMap = new TreeMap<>(); while (in.hasNext()) { @@ -26,15 +25,29 @@ public static void main(String[] args) Character c = word.charAt(0); // Update the map here - // Modify Worked Example 15.1 - . . . + if (word.length() > 0) { - - } + if (firstLetterMap.containsKey(c)) { + // If the key exists, add the word to the corresponding set + Set existingSet = firstLetterMap.get(c); + existingSet.add(word); // Add word to the set + } else { + // If the key does not exist, create a new set with the word + Set newSet = new TreeSet<>(); // TreeSet to automatically sort + newSet.add(word); + firstLetterMap.put(c, newSet); // Put the new set in the map + } + } + } + // Print the map here in this form // a: [a, able, aardvark] - . . . + + + for (Map.Entry> entry : firstLetterMap.entrySet()) { + System.out.println(entry.getKey() + ": " + entry.getValue()); + } } catch (FileNotFoundException e) { System.out.println("Cannot open: " + filename); @@ -54,4 +67,5 @@ public static String clean(String s) } return r.toLowerCase(); } + //in.close(); } diff --git a/Chapter 15 Activities/StringLengthMap/src/StringLengthMap.java b/Chapter 15 Activities/StringLengthMap/src/StringLengthMap.java index 0a3f44a4e..452920047 100644 --- a/Chapter 15 Activities/StringLengthMap/src/StringLengthMap.java +++ b/Chapter 15 Activities/StringLengthMap/src/StringLengthMap.java @@ -12,26 +12,30 @@ public class StringLengthMap { public static void main(String[] args) throws FileNotFoundException { - String filename = "src/test1.txt"; + String filename = "Chapter 15 Activities/StringLengthMap/src/test1.txt"; try (Scanner in = new Scanner(new File(filename))) { - - // Create your map here - + Map freq = new TreeMap<>(); while (in.hasNext()) { String word = clean(in.next()); Integer len = word.length(); - - // Update the map here - // Modify Worked Example 15.1 - - - + if(word.length()>0){ + if(freq.containsKey(len)){ + String current = freq.get(len); + freq.put(len, current +","+ word); + } + else{ + freq.put(len,word); + } + + + }} + for (Integer len : freq.keySet()) { + System.out.println(len + ": " + freq.get(len)); } - // Print the strings, in increasing order of their length // Use this format: 1: i, a, i } catch (FileNotFoundException e) diff --git a/Chapter 15 Activities/StringLengthMap/src/StringLengthMap2.java b/Chapter 15 Activities/StringLengthMap/src/StringLengthMap2.java index bfc5eff95..79ea3f90f 100644 --- a/Chapter 15 Activities/StringLengthMap/src/StringLengthMap2.java +++ b/Chapter 15 Activities/StringLengthMap/src/StringLengthMap2.java @@ -12,26 +12,33 @@ public class StringLengthMap2 { public static void main(String[] args) { - String filename = "src/test1.txt"; + String filename = "Chapter 15 Activities/StringLengthMap/src/test1.txt"; try (Scanner in = new Scanner(new File(filename))) { - // Create your map here + Map freq = new TreeMap<>(); while (in.hasNext()) { String word = clean(in.next()); Integer len = word.length(); + if (word.length() > 0) { + // Use merge to add or update the entry + freq.merge(len, word, (existing, newWord) -> existing + "," + newWord);} + } + // Update the map here // Use the Java 8 merge() method + + for (Integer len : freq.keySet()) { + System.out.println(len + ": " + freq.get(len)); } - // Print the strings, in increasing order of their length // Use this format: 1: i, a, i } catch (FileNotFoundException e) From e1f044fdfa7b706514c40b907b413690c95f6fe4 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Mon, 15 Sep 2025 13:07:06 -0500 Subject: [PATCH 11/29] stacks --- Chapter 15 Class Notes/src/StackDemo.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Chapter 15 Class Notes/src/StackDemo.java b/Chapter 15 Class Notes/src/StackDemo.java index e8523604c..83a00c47e 100644 --- a/Chapter 15 Class Notes/src/StackDemo.java +++ b/Chapter 15 Class Notes/src/StackDemo.java @@ -9,5 +9,22 @@ public class StackDemo { public static void main(String[] args) { + Stack commands = new Stack<>(); + //push a bunch of commands onto the top of the stack + commands.push("Insert: 'Hello'"); + commands.push("Insert: ','"); + commands.push("Insert: ' '"); + commands.push("Insert: 'World;"); + commands.push("Insert: '?'"); + commands.push("Insert: '!'"); + + //print the stack the top of the stack is the far right + System.out.println(commands); + + //simulate the user pressing undo 4 times + for (int i=0; i<4; i++){ + System.out.println("Undo "+commands.pop()); + } + System.out.println(commands); } } From eadbee8cc7e0cea223b078242510fe83d460897f Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Tue, 16 Sep 2025 13:20:56 -0500 Subject: [PATCH 12/29] priorityqueue notes --- .../src/PriorityQueueDemo.java | 40 ++++++++++++++++++- Chapter 15 Class Notes/src/QueueDemo.java | 35 ++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/Chapter 15 Class Notes/src/PriorityQueueDemo.java b/Chapter 15 Class Notes/src/PriorityQueueDemo.java index e27bc2c81..c211413cc 100644 --- a/Chapter 15 Class Notes/src/PriorityQueueDemo.java +++ b/Chapter 15 Class Notes/src/PriorityQueueDemo.java @@ -10,5 +10,41 @@ public class PriorityQueueDemo { public static void main(String[] args) { - } -} + + //create a priority queue of strings + //a priority needs to be composed of comparable objects + + Queue students = new PriorityQueue<>(); + students.add("Neel"); + students.add("Jonathan"); + students.add("Cam"); + students.add("Kaitlyn"); + students.add("Dylan"); + + // the next highest priorty object is moved to the front of the queue + //when the head of the queue is removed + while(students.size()>0){ + System.out.println(students.remove()); + } + + //create a to-do lis + //the workorder class has a priority and description + Queue toDo = new PriorityQueue<>(); + + //lower priority is more important + toDo.add(new WorkOrder(3,"Water Plants")); + toDo.add(new WorkOrder(2,"Make Dinner")); + toDo.add(new WorkOrder(1,"Conquer World")); + toDo.add(new WorkOrder(9,"Play Videogames")); + toDo.add(new WorkOrder(1,"Study for the test")); + + //objects are NOT stored in priority order + System.out.println(toDo); + + //objects will be removed in priority order + while(toDo.size()>0){ + System.out.println(toDo.remove()); + } + + +}} diff --git a/Chapter 15 Class Notes/src/QueueDemo.java b/Chapter 15 Class Notes/src/QueueDemo.java index 1da9ca974..b19ff1282 100644 --- a/Chapter 15 Class Notes/src/QueueDemo.java +++ b/Chapter 15 Class Notes/src/QueueDemo.java @@ -9,5 +9,40 @@ public class QueueDemo { public static void main(String[] args) { + // create a print queue of strings using a linkedlist + Queue jobs = new LinkedList<>(); + + //add some print jobs + jobs.add("Harry: Quarter 2 Expense Report"); + jobs.add("Conner: Recipe for banana bread"); + jobs.add("Katherine: Top secret document"); + + System.out.println("Printing: "+jobs.remove()); + + //add some more print jobs + jobs.add("Vardhan: Grocery List"); + jobs.add("Katherine: Really top secret document"); + jobs.add("Katherine: Can I get fired for this?"); + + System.out.println("Printing: "+jobs.remove()); + System.out.println("Printing: "+jobs.remove()); + + jobs.add("Boss: Katherine Termination Letter"); + + //print the rest of the jobs in the queue + /* + int numjobs = jobs.size(); + for(int i=0;i0){ + System.out.println("Printing" +jobs.remove()); + } } } From a7f26eed6ad1e06c79cd2638a4c8baa1855a516e Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Fri, 19 Sep 2025 13:17:16 -0500 Subject: [PATCH 13/29] driveway --- Chapter 15 Activities/Driveway/src/Driveway.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Chapter 15 Activities/Driveway/src/Driveway.java b/Chapter 15 Activities/Driveway/src/Driveway.java index 64c94cfc1..f6a4f27bc 100644 --- a/Chapter 15 Activities/Driveway/src/Driveway.java +++ b/Chapter 15 Activities/Driveway/src/Driveway.java @@ -10,10 +10,12 @@ public class Driveway /** * Stack representing the cars in the driveway. */ + private Stack driveway; /** * Stack representing the cars in the street. */ + private Stack street; /** @@ -21,8 +23,8 @@ public class Driveway */ public Driveway() { - // Complete the constructor - ... + driveway = new Stack<>(); + street= new Stack<>(); } @@ -35,7 +37,7 @@ public Driveway() public void add(int licensePlate) { // Complete this method - ... + driveway.push(licensePlate); } @@ -48,7 +50,7 @@ public void add(int licensePlate) public void remove(int licensePlate) { // Complete this method - ... + driveway.pop(); } @@ -60,11 +62,11 @@ public void print() { System.out.println("In Driveway, starting at first in (one license plate per line):"); // Print the cars in the driveway here - ... + System.out.println(driveway); System.out.println("In Street, starting at first in (one license plate per line):"); // Print the cars in the street here - ... + System.out.println(street); } } From ab718272d6772a4e018ea98a1de2418a740b6c9d Mon Sep 17 00:00:00 2001 From: shriya Date: Sun, 21 Sep 2025 17:42:15 -0500 Subject: [PATCH 14/29] programs done --- .vscode/launch.json | 21 ++++++ .../Driveway/src/Driveway.java | 13 +++- Chapter 15 Activities/FloodFill/src/Grid.java | 43 +++++++++++- .../FloodFillQueue/src/Grid.java | 55 ++++++++++++---- .../HTMLChecker/src/HTMLChecker.java | 65 ++++++++++++------- 5 files changed, 155 insertions(+), 42 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 5beffa6a5..497d8f73b 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,27 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "type": "java", + "name": "HTMLChecker", + "request": "launch", + "mainClass": "HTMLChecker", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "FloodFillTester", + "request": "launch", + "mainClass": "FloodFillTester", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "DrivewayDemo", + "request": "launch", + "mainClass": "DrivewayDemo", + "projectName": "data-structures_addf3fee" + }, { "type": "java", "name": "Current File", diff --git a/Chapter 15 Activities/Driveway/src/Driveway.java b/Chapter 15 Activities/Driveway/src/Driveway.java index f6a4f27bc..a01f63b33 100644 --- a/Chapter 15 Activities/Driveway/src/Driveway.java +++ b/Chapter 15 Activities/Driveway/src/Driveway.java @@ -50,11 +50,18 @@ public void add(int licensePlate) public void remove(int licensePlate) { // Complete this method - driveway.pop(); + while (!driveway.isEmpty() && driveway.peek() != licensePlate) { + int car = driveway.pop(); + street.push(car);} + if (!driveway.isEmpty() && driveway.peek() == licensePlate) { + driveway.pop();} + - } - +//after a car is taken out, the ones on the street are always returned to the driveway + while (!street.isEmpty()) { + int car = street.pop(); + driveway.push(car);}} /** * Prints the driveway and street details to the screen. */ diff --git a/Chapter 15 Activities/FloodFill/src/Grid.java b/Chapter 15 Activities/FloodFill/src/Grid.java index 1280e3eb3..8c55c0644 100644 --- a/Chapter 15 Activities/FloodFill/src/Grid.java +++ b/Chapter 15 Activities/FloodFill/src/Grid.java @@ -1,16 +1,53 @@ +import java.util.Stack; + public class Grid { private static final int SIZE = 10; int[][] pixels = new int[SIZE][SIZE]; - . . . + + + + private static class Pair { + int row, col; + Pair(int row, int col) { + this.row = row; + this.col = col; + } + } /** * Flood fill, starting with the given row and column. */ - public void floodfill(int row, int column) + public void floodfill(int startRow, int startCol) { - . . . + Stack stack = new Stack<>(); + int fillValue = 1; + + stack.push(new Pair(startRow, startCol)); + + while (!stack.isEmpty()) { + Pair current = stack.pop(); + int row = current.row; + int col = current.col; + + if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) { + continue; + } + + if (pixels[row][col] != 0) { + continue; + } + + pixels[row][col] = fillValue; + fillValue++; + + stack.push(new Pair(row - 1, col)); // North + stack.push(new Pair(row, col + 1)); // East + stack.push(new Pair(row + 1, col)); // South + stack.push(new Pair(row, col - 1)); // West + } } + @Override public String toString() diff --git a/Chapter 15 Activities/FloodFillQueue/src/Grid.java b/Chapter 15 Activities/FloodFillQueue/src/Grid.java index 181f97b00..0529037ad 100644 --- a/Chapter 15 Activities/FloodFillQueue/src/Grid.java +++ b/Chapter 15 Activities/FloodFillQueue/src/Grid.java @@ -1,25 +1,52 @@ -. . . -public class Grid -{ +import java.util.LinkedList; +import java.util.Queue; + +public class Grid { private static final int SIZE = 10; int[][] pixels = new int[SIZE][SIZE]; - . . . /** * Flood fill, starting with the given row and column. - */ - public void floodfill(int row, int column) - { - . . . + */ + public void floodfill(int startRow, int startCol) { + Queue queue = new LinkedList<>(); + int fillValue = 1; + + queue.add(new Pair(startRow, startCol)); + + while (!queue.isEmpty()) { + Pair current = queue.remove(); + int row = current.getRow(); + int col = current.getColumn(); + + // Bounds check + if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) { + continue; + } + + // Already filled + if (pixels[row][col] != 0) { + continue; + } + + // Fill pixel + pixels[row][col] = fillValue++; + + // Enqueue neighbors in N, E, S, W order + queue.add(new Pair(row - 1, col)); // North + queue.add(new Pair(row, col + 1)); // East + queue.add(new Pair(row + 1, col)); // South + queue.add(new Pair(row, col - 1)); // West + } } - public String toString() - { + @Override + public String toString() { String r = ""; - for (int i = 0; i < SIZE; i++) - { - for (int j = 0; j < SIZE; j++) - r = r + String.format("%3d", pixels[i][j]); + for (int i = 0; i < SIZE; i++) { + for (int j = 0; j < SIZE; j++) { + r = r + String.format("%4d", pixels[i][j]); + } r = r + "\n"; } return r; diff --git a/Chapter 15 Activities/HTMLChecker/src/HTMLChecker.java b/Chapter 15 Activities/HTMLChecker/src/HTMLChecker.java index 87fee8638..641a7003e 100644 --- a/Chapter 15 Activities/HTMLChecker/src/HTMLChecker.java +++ b/Chapter 15 Activities/HTMLChecker/src/HTMLChecker.java @@ -2,33 +2,54 @@ import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Stack; + /** - * Write a program that checks whether a sequence of HTML tags - * is properly nested. For each opening tag, such as

, there - * must be a closing tag

. A tag such as

may have other - * tags inside, for example

- *

- * The inner tags must be closed before the outer ones. - * Your program should process a file containing tags. - * For simplicity, assume that the tags are separated by - * spaces, and that there is no text inside the tags. -*/ -public class HTMLChecker -{ - public static void main(String[] args) - { - String filename = "src/TagSample1.html"; + * Checks whether HTML tags are properly nested. + */ +public class HTMLChecker { + public static void main(String[] args) { + String filename = "Chapter 15 Activities/HTMLChecker/src/TagSample1.html"; + Stack tagStack = new Stack<>(); + boolean check = true; + + try (Scanner in = new Scanner(new File(filename))) { + while (in.hasNext()) { + String tag = in.next(); - try (Scanner in = new Scanner(new File(filename))) - { - // Your code goes here - . . . + if (tag.startsWith(" with no opening tag."); + check = false; + break; + } + String open = tagStack.pop(); + if (!open.equals(close)) { + System.out.println("Error: Tag mismatch. Expected , found ."); + check = false; + break; + } + } else if (tag.startsWith("<")) { + // Opening tag + String open = tag.substring(1, tag.length() - 1); + tagStack.push(open); + } + } - } catch (FileNotFoundException e) - { + if (check) { + if (tagStack.isEmpty()) { + System.out.println("Tags are properly nested."); + } else { + System.out.println("Error: Unclosed tags remaining:"); + while (!tagStack.isEmpty()) { + System.out.println("Unclosed: <" + tagStack.pop() + ">"); + } + } + } + + } catch (FileNotFoundException e) { System.out.println("Cannot open: " + filename); } - } } From c93112b8aa2f34450c46bbc2a014929c7ac8f44e Mon Sep 17 00:00:00 2001 From: shriya Date: Sun, 21 Sep 2025 17:45:13 -0500 Subject: [PATCH 15/29] drivweay --- .../Driveway/src/Driveway.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/Chapter 15 Activities/Driveway/src/Driveway.java b/Chapter 15 Activities/Driveway/src/Driveway.java index a01f63b33..3dbcf58b9 100644 --- a/Chapter 15 Activities/Driveway/src/Driveway.java +++ b/Chapter 15 Activities/Driveway/src/Driveway.java @@ -66,14 +66,16 @@ public void remove(int licensePlate) * Prints the driveway and street details to the screen. */ public void print() - { - System.out.println("In Driveway, starting at first in (one license plate per line):"); - // Print the cars in the driveway here - System.out.println(driveway); - - System.out.println("In Street, starting at first in (one license plate per line):"); - // Print the cars in the street here - System.out.println(street); +{ + System.out.println("In Driveway, starting at first in (one license plate per line):"); + for (int car : driveway) { + System.out.println(car); + } + System.out.println("In Street, starting at first in (one license plate per line):"); + for (int car : street) { + System.out.println(car); } } + +} From 2d79e82e944ca2fb3ab3dbff4c9fa455ac0edfb0 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Thu, 25 Sep 2025 13:24:44 -0500 Subject: [PATCH 16/29] dfghh --- Chapter 16 Class Notes/src/LinkedList.java | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/Chapter 16 Class Notes/src/LinkedList.java b/Chapter 16 Class Notes/src/LinkedList.java index 11b0b9ba1..d4dc4b575 100644 --- a/Chapter 16 Class Notes/src/LinkedList.java +++ b/Chapter 16 Class Notes/src/LinkedList.java @@ -9,11 +9,18 @@ public class LinkedList { + //first refers to the first node in the list + //if the list is empty, first will be null + private Node first; + /** Constructs an empty linked list. */ + public LinkedList(){ + this.first = null; + } @@ -21,8 +28,12 @@ public class LinkedList Returns the first element in the linked list. @return the first element in the linked list */ - - + public Object element(){ + if(this.first == null){ + throw new NoSuchElementException(); + } + return this.first.data; + } /** @@ -53,6 +64,12 @@ public class LinkedList //Class Node + //Node is static because it does NOT need to access anything in LinkedList + //The object will store information, not interact + static class Node{ + public Node next; + public Object data; + } class LinkedListIterator //implements ListIterator From ff312af91848370db4a35cc50c6fda77fe13bce7 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Fri, 26 Sep 2025 13:17:36 -0500 Subject: [PATCH 17/29] ll notes --- Chapter 16 Class Notes/src/LinkedList.java | 111 +++++++++++++++++++-- Chapter 16 Class Notes/src/ListDemo.java | 8 ++ 2 files changed, 110 insertions(+), 9 deletions(-) diff --git a/Chapter 16 Class Notes/src/LinkedList.java b/Chapter 16 Class Notes/src/LinkedList.java index d4dc4b575..63fa6d9e8 100644 --- a/Chapter 16 Class Notes/src/LinkedList.java +++ b/Chapter 16 Class Notes/src/LinkedList.java @@ -40,7 +40,14 @@ public Object element(){ Removes the first element in the linked list. @return the removed element */ - + public Object removeFirst(){ + if(this.first == null){ + throw new NoSuchElementException(); + } + Object element = this.first.data; + this.first = this.first.next; + return element; + } @@ -49,8 +56,12 @@ public Object element(){ Adds an element to the front of the linked list. @param element the element to add */ - - + public void addFirst(Object e){ + Node newNode = new Node(); + newNode.data = e; + newNode.next = this.first; + this.first = newNode; + } @@ -58,9 +69,18 @@ public Object element(){ Returns an iterator for iterating through this list. @return an iterator for iterating through this list */ + public ListIterator listIterator(){ + return new LinkedListIterator(); + } - - + public String toString(){ + ListIterator listIterator = listIterator(); + String allElements = "["; + while(listIterator.hasNext()){ + allElements += listIterator.next()+", "; + } + return allElements+"]"; + } //Class Node @@ -72,22 +92,45 @@ static class Node{ } - class LinkedListIterator //implements ListIterator + class LinkedListIterator implements ListIterator { //private data + private Node position; + private Node previous; + private boolean isAfterNext; /** Constructs an iterator that points to the front of the linked list. */ - + public LinkedListIterator(){ + position=null; + previous=null; + isAfterNext = false; + } /** Moves the iterator past the next element. @return the traversed element */ + public Object next(){ + if (!hasNext()){ + throw new NoSuchElementException(); + } + + previous = position; + if (position==null){ + position=first; + } + else{ + position=position.next; + } + isAfterNext = true; + + return position.data; + } @@ -97,13 +140,40 @@ class LinkedListIterator //implements ListIterator @return true if there is an element after the iterator position */ + public boolean hasNext(){ + //check if list is empty + if(position == null){ + return first !=null; + } + + //the iterator has moved so check the next node + return position.next != null; + } + /** Adds an element before the iterator position and moves the iterator past the inserted element. @param element the element to add */ - + public void add(Object element){ + //check if the iterator is at the beginning of the list + if (position==null){ + addFirst(element); + position=first; + } + else{ + Node newNode = new Node(); + newNode.data = element; + newNode.next = position.next; + + //set the next element of the CURRENT position to point to our new node + position.next = newNode; + position = newNode; + } + + isAfterNext = false; + } @@ -113,7 +183,23 @@ class LinkedListIterator //implements ListIterator Removes the last traversed element. This method may only be called after a call to the next() method. */ - + public void remove(){ + if(!isAfterNext){ + throw new IllegalStateException(); + } + + //check if the iterator is at the beginninng + if(position==first){ + removeFirst(); + position = null; + } + else{ + previous.next = position.next; + position=previous; + } + + isAfterNext = false; + } @@ -124,7 +210,14 @@ only be called after a call to the next() method. Sets the last traversed element to a different value. @param element the element to set */ + public void set(Object element){ + if(!isAfterNext){ + throw new IllegalStateException(); + } + position.data = element; + //we don't have to reset isAfterNext because the structure of the list has not changed + } diff --git a/Chapter 16 Class Notes/src/ListDemo.java b/Chapter 16 Class Notes/src/ListDemo.java index 36dcfe962..86549eadd 100644 --- a/Chapter 16 Class Notes/src/ListDemo.java +++ b/Chapter 16 Class Notes/src/ListDemo.java @@ -5,5 +5,13 @@ public class ListDemo { public static void main(String[] args) { + LinkedList students = new LinkedList(); + + students.addFirst("Cam"); + students.addFirst("Conner"); + students.addFirst("Catherine"); + students.addFirst("Jonathan"); + + System.out.println(students); } } From 627561ea12ddeca58546a760188ba856b73f5a17 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Mon, 29 Sep 2025 13:17:18 -0500 Subject: [PATCH 18/29] yu --- Chapter 16 Activities/Contains/src/LinkedList.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Chapter 16 Activities/Contains/src/LinkedList.java b/Chapter 16 Activities/Contains/src/LinkedList.java index e8eb656bd..9b79a121a 100644 --- a/Chapter 16 Activities/Contains/src/LinkedList.java +++ b/Chapter 16 Activities/Contains/src/LinkedList.java @@ -41,7 +41,18 @@ public int size() */ public boolean contains(Object obj) { - // ... + Boolean check = true; + for(int i=0; i Date: Mon, 29 Sep 2025 21:31:22 -0500 Subject: [PATCH 19/29] contains --- .vscode/launch.json | 7 ++++++ .../Contains/src/LinkedList.java | 22 +++++++++---------- .../Contains/src/ListTester.java | 2 +- Chapter 16 Class Notes/src/LinkedList.java | 6 +++++ 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 497d8f73b..154d2303a 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,13 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "type": "java", + "name": "ListTester", + "request": "launch", + "mainClass": "ListTester", + "projectName": "data-structures_addf3fee" + }, { "type": "java", "name": "HTMLChecker", diff --git a/Chapter 16 Activities/Contains/src/LinkedList.java b/Chapter 16 Activities/Contains/src/LinkedList.java index 9b79a121a..859f06c1b 100644 --- a/Chapter 16 Activities/Contains/src/LinkedList.java +++ b/Chapter 16 Activities/Contains/src/LinkedList.java @@ -41,18 +41,18 @@ public int size() */ public boolean contains(Object obj) { - Boolean check = true; - for(int i=0; i Date: Mon, 29 Sep 2025 23:29:13 -0500 Subject: [PATCH 20/29] changes --- .vscode/launch.json | 7 ++ .../Contains/src/LinkedList.java | 106 +++++------------- .../Size/src/LinkedList.java | 16 ++- 3 files changed, 45 insertions(+), 84 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 154d2303a..603bce57e 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,13 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "type": "java", + "name": "SizeTester", + "request": "launch", + "mainClass": "SizeTester", + "projectName": "data-structures_addf3fee" + }, { "type": "java", "name": "ListTester", diff --git a/Chapter 16 Activities/Contains/src/LinkedList.java b/Chapter 16 Activities/Contains/src/LinkedList.java index 859f06c1b..244b30771 100644 --- a/Chapter 16 Activities/Contains/src/LinkedList.java +++ b/Chapter 16 Activities/Contains/src/LinkedList.java @@ -35,30 +35,38 @@ public int size() } /** - Checks if this linked list contains the given object. + Checks if this linked list contains the given object (recursive version). @param obj The object to be checked for. - @return If the object exists in the list. + @return true if the object exists in the list, false otherwise. */ public boolean contains(Object obj) { - Node current = first; - while (current != null) - { - if (obj == null && current.data == null) { - return true; - } - if (obj != null && obj.equals(current.data)) { - return true; - } - current = current.next; - } - return false; + return contains(first, obj); } /** - Returns the first element in the linked list. - @return the first element in the linked list + Recursive helper method for contains. + @param start The current node in the recursion. + @param obj The object to search for. + @return true if found, false otherwise. */ + private static boolean contains(Node start, Object obj) + { + if (start == null) { + return false; + } + + if (obj == null && start.data == null) { + return true; + } + + if (obj != null && obj.equals(start.data)) { + return true; + } + + return contains(start.next, obj); + } + public Object getFirst() { if (first == null) @@ -66,10 +74,6 @@ public Object getFirst() return first.data; } - /** - Removes the first element in the linked list. - @return the removed element - */ public Object removeFirst() { if (first == null) @@ -77,17 +81,11 @@ public Object removeFirst() Object element = first.data; first = first.next; currentSize--; - // clear old cached data last = null; lastIndex = -1; - // return removed element return element; } - /** - Adds an element to the front of the linked list. - @param element the element to add - */ public void addFirst(Object element) { Node newNode = new Node(); @@ -95,16 +93,10 @@ public void addFirst(Object element) newNode.next = first; first = newNode; currentSize++; - // clear old cached data last = null; lastIndex = -1; } - /** - Gets the object at the given index. - @param n The index of the object. - @return The object at the given index. - */ public Object get(int n) { if ((lastIndex == -1) || (lastIndex >= n)) @@ -120,23 +112,12 @@ public Object get(int n) return last.data; } - /** - Sets the object at the given index. - @param n The index of the object to be set. - @param newElement The object to set. - */ public void set(int n, Object newElement) { Node node = getNode(first, n); node.data = newElement; } - /** - Gets the node at the given index. - @param start The start node to count from. - @param distance The index of the object to get. - @return The node at the given object. - */ private static Node getNode(Node start, int distance) { if ((distance <= 0) || (start == null)) @@ -144,10 +125,6 @@ private static Node getNode(Node start, int distance) return getNode(start.next, distance - 1); } - /** - Returns an iterator for iterating through this list. - @return an iterator for iterating through this list - */ public ListIterator listIterator() { return new LinkedListIterator(); @@ -164,40 +141,24 @@ private class LinkedListIterator implements ListIterator private Node position; private Node previous; - /** - Constructs an iterator that points to the front - of the linked list. - */ public LinkedListIterator() { position = null; previous = null; } - /** - Moves the iterator past the next element. - @return the traversed element - */ public Object next() { if (!hasNext()) throw new NoSuchElementException(); - previous = position; // Remember for remove - + previous = position; if (position == null) position = first; else position = position.next; - return position.data; } - /** - Tests if there is an element after the iterator - position. - @return true if there is an element after the iterator - position - */ public boolean hasNext() { if (position == null) @@ -206,11 +167,6 @@ public boolean hasNext() return position.next != null; } - /** - Adds an element before the iterator position - and moves the iterator past the inserted element. - @param element the element to add - */ public void add(Object element) { if (position == null) @@ -230,15 +186,10 @@ public void add(Object element) previous = position; } - /** - Removes the last traversed element. This method may - only be called after a call to the next() method. - */ public void remove() { if (previous == position) throw new IllegalStateException(); - if (position == first) { removeFirst(); @@ -251,11 +202,6 @@ public void remove() position = previous; } - /** - Sets the last traversed element to a different - value. - @param element the element to set - */ public void set(Object element) { if (position == null) @@ -263,4 +209,4 @@ public void set(Object element) position.data = element; } } -} \ No newline at end of file +} diff --git a/Chapter 16 Activities/Size/src/LinkedList.java b/Chapter 16 Activities/Size/src/LinkedList.java index bc0ff8757..2d56f3b56 100644 --- a/Chapter 16 Activities/Size/src/LinkedList.java +++ b/Chapter 16 Activities/Size/src/LinkedList.java @@ -19,14 +19,22 @@ public LinkedList() } /** - Computes the size of the linked list. - @return the number of elements in the list - */ + Computes the size of the linked list by traversing the nodes. + @return the number of elements in the list +*/ public int size() { - . . . + int count = 0; + Node current = first; + while (current != null) + { + count++; + current = current.next; + } + return count; } + /** Returns the first element in the linked list. @return the first element in the linked list From be2a6853176a19edb115151bd9c09d9e911c90c0 Mon Sep 17 00:00:00 2001 From: shriya Date: Mon, 29 Sep 2025 23:52:28 -0500 Subject: [PATCH 21/29] DONE --- .../Contains/src/LinkedList.java | 20 ++++++++++++++++ .../Size/src/LinkedList.java | 24 +++++++++++++++++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/Chapter 16 Activities/Contains/src/LinkedList.java b/Chapter 16 Activities/Contains/src/LinkedList.java index 244b30771..9ef00d84a 100644 --- a/Chapter 16 Activities/Contains/src/LinkedList.java +++ b/Chapter 16 Activities/Contains/src/LinkedList.java @@ -44,6 +44,26 @@ public boolean contains(Object obj) return contains(first, obj); } + + /* CONTAINS METHOD WITHOUT ITERATOR + public boolean contains(Object obj) + { + Node current = first; + while (current != null) + { + if (obj == null && current.data == null) { + return true; + } + if (obj != null && obj.equals(current.data)) { + return true; + } + current = current.next; + } + return false; + }*/ + + + /** Recursive helper method for contains. @param start The current node in the recursion. diff --git a/Chapter 16 Activities/Size/src/LinkedList.java b/Chapter 16 Activities/Size/src/LinkedList.java index 2d56f3b56..e3efc9aac 100644 --- a/Chapter 16 Activities/Size/src/LinkedList.java +++ b/Chapter 16 Activities/Size/src/LinkedList.java @@ -21,7 +21,7 @@ public LinkedList() /** Computes the size of the linked list by traversing the nodes. @return the number of elements in the list -*/ + public int size() { int count = 0; @@ -32,8 +32,28 @@ public int size() current = current.next; } return count; - } + }*/ +/** + Computes the size of the linked list recursively. + @return the number of elements in the list +*/ +public int size() +{ + return size(first); +} + +/** + Recursive helper method to compute size. + @param start The node to start counting from. + @return The number of nodes from start to end. +*/ +private static int size(Node start) +{ + if (start == null) + return 0; + return 1 + size(start.next); +} /** Returns the first element in the linked list. From 29ab7f39984d2613c3fb15aa1236c7c719f8cd21 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Tue, 30 Sep 2025 13:29:56 -0500 Subject: [PATCH 22/29] notes --- .../src/CircularArrayQueue.java | 40 ++++++++++++++++--- .../src/LinkedListStack.java | 19 ++++++++- Chapter 16 Class Notes/src/QueueDemo.java | 5 ++- Chapter 16 Class Notes/src/StackDemo.java | 4 +- 4 files changed, 57 insertions(+), 11 deletions(-) diff --git a/Chapter 16 Class Notes/src/CircularArrayQueue.java b/Chapter 16 Class Notes/src/CircularArrayQueue.java index bee3df2f6..38b9dd0aa 100644 --- a/Chapter 16 Class Notes/src/CircularArrayQueue.java +++ b/Chapter 16 Class Notes/src/CircularArrayQueue.java @@ -7,13 +7,21 @@ public class CircularArrayQueue { private Object[] elements; //private data - + private int currentSize; + private int head; + private int tail; /** Constructs an empty queue. */ - + public CircularArrayQueue(){ + final int INITIAL_SIZE = 3; + this.elements = new Object[INITIAL_SIZE]; + head =0; + tail=0; + currentSize=0; //queue is empty when we first created it + } @@ -23,7 +31,9 @@ public class CircularArrayQueue Checks whether this queue is empty. @return true if this queue is empty */ - + public boolean empty(){ + return currentSize==0; + } @@ -31,7 +41,15 @@ public class CircularArrayQueue Adds an element to the tail of this queue. @param newElement the element to add */ - + public void add(Object element){ + this.currentSize++; + this.elements[this.tail] = element; + this.tail++; + //reset the tail to 0 when it reaches the size of the array + this.tail %= this.elements.length; + + growIfNecessary(); + } @@ -40,7 +58,17 @@ public class CircularArrayQueue Removes an element from the head of this queue. @return the removed element */ + public Object remove(){ + if(this.empty()){ + throw new NoSuchElementException(); + } + this.currentSize--; + Object element = this.elements[this.head]; + //reset the head to 0 if we reach the end of the array + this.head = (this.head +1)% this.elements.length; + return element; + } @@ -50,7 +78,7 @@ public class CircularArrayQueue */ private void growIfNecessary() { - /* + if(this.currentSize == this.elements.length) { Object[] newElements = new Object[2 * this.elements.length]; @@ -62,7 +90,7 @@ private void growIfNecessary() this.head = 0; this.tail = this.currentSize; } - */ + } diff --git a/Chapter 16 Class Notes/src/LinkedListStack.java b/Chapter 16 Class Notes/src/LinkedListStack.java index e12647ae1..38fa72d60 100644 --- a/Chapter 16 Class Notes/src/LinkedListStack.java +++ b/Chapter 16 Class Notes/src/LinkedListStack.java @@ -20,6 +20,13 @@ public LinkedListStack() * * @param element the element to add */ + public void push (Object element){ + // Always push elements to the front of the linked list + Node newNode = new Node(); + newNode.data = element; + newNode.next = this.first; + this.first = newNode; + } @@ -30,7 +37,14 @@ public LinkedListStack() Removes the element from the top of the stack. @return the removed element */ - + public Object pop(){ + if(this.empty()){ + throw new NoSuchElementException(); + } + Object element = this.first.data; + this.first = this.first.next; + return element; + } @@ -43,6 +57,9 @@ public LinkedListStack() * * @return true if the stack is empty */ + public boolean empty(){ + return this.first==null; + } static class Node diff --git a/Chapter 16 Class Notes/src/QueueDemo.java b/Chapter 16 Class Notes/src/QueueDemo.java index 696b7f3f2..7b7399425 100644 --- a/Chapter 16 Class Notes/src/QueueDemo.java +++ b/Chapter 16 Class Notes/src/QueueDemo.java @@ -2,12 +2,13 @@ public class QueueDemo { public static void main(String[] args) { - /* + CircularArrayQueue queue = new CircularArrayQueue(); queue.add("Tom"); queue.add("Diana"); queue.add("Harry"); + queue.add("sam"); System.out.println(queue.remove()); // remove Tom queue.add("Romeo"); System.out.println(queue.remove()); // remove Diana @@ -20,6 +21,6 @@ public static void main(String[] args) } System.out.println("Expected output: Tom, Diana, Harry, Romeo, Juliet, Maria"); - */ + } } diff --git a/Chapter 16 Class Notes/src/StackDemo.java b/Chapter 16 Class Notes/src/StackDemo.java index d093e087a..c23f82261 100644 --- a/Chapter 16 Class Notes/src/StackDemo.java +++ b/Chapter 16 Class Notes/src/StackDemo.java @@ -2,7 +2,7 @@ public class StackDemo { public static void main(String[] args) { - /* + LinkedListStack stack = new LinkedListStack(); stack.push("Tom"); @@ -15,6 +15,6 @@ public static void main(String[] args) } System.out.println("Expected: Harry Diana Tom"); - */ + } } From 73a9f0ab2390bd583e771e7794553c8c7ccdf3d9 Mon Sep 17 00:00:00 2001 From: shriyak26 Date: Thu, 2 Oct 2025 13:29:08 -0500 Subject: [PATCH 23/29] uiuk --- Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java b/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java index 349635151..423d568c3 100644 --- a/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java +++ b/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java @@ -23,9 +23,7 @@ public LinkedListQueue() */ public void firstToLast() { - . . . - - + head = } From 53de1f6810e0c7f7bb2af6cc6337a98dcb5415fd Mon Sep 17 00:00:00 2001 From: shriya Date: Thu, 2 Oct 2025 22:13:52 -0500 Subject: [PATCH 24/29] programs --- .vscode/launch.json | 7 +++++++ .../FirstToLast/src/LinkedListQueue.java | 11 +++++++++- .../LastToFirst/src/LinkedListQueue.java | 20 ++++++++++++++----- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 603bce57e..786bb7e03 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,13 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "type": "java", + "name": "QueueTester", + "request": "launch", + "mainClass": "QueueTester", + "projectName": "data-structures_addf3fee" + }, { "type": "java", "name": "SizeTester", diff --git a/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java b/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java index 423d568c3..9a3e6cf75 100644 --- a/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java +++ b/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java @@ -23,7 +23,16 @@ public LinkedListQueue() */ public void firstToLast() { - head = + if (head == null || head.next == null) + { + return; + } + Node first = head; + head=head.next; + first.next = null; + tail.next = first; + + } diff --git a/Chapter 16 Activities/LastToFirst/src/LinkedListQueue.java b/Chapter 16 Activities/LastToFirst/src/LinkedListQueue.java index c636cb1ef..9579a177f 100644 --- a/Chapter 16 Activities/LastToFirst/src/LinkedListQueue.java +++ b/Chapter 16 Activities/LastToFirst/src/LinkedListQueue.java @@ -22,11 +22,21 @@ public LinkedListQueue() */ public void lastToFirst() { - . . . - - - - + if (head == null || head.next == null) + { + return; + } + Node current=head; + Node prev = tail; + while (current.next != null) + { + prev = current; + current = current.next; + } + prev.next = null; + tail = prev; + current.next = head; + head = current; } From 212c691851d8fa500349cd3b0b7c927c1758bd01 Mon Sep 17 00:00:00 2001 From: shriya Date: Tue, 4 Nov 2025 23:41:25 -0600 Subject: [PATCH 25/29] finished binary tree and tree code --- .vscode/launch.json | 14 ++++++ .../CountLeaves/src/Tree.java | 24 ++++++++++ .../src/BinaryTree.java | 48 ++++++++++++++----- Chapter 17 Class Notes/src/BinaryTree.java | 40 +++++++++++----- Chapter 17 Class Notes/src/Tree.java | 25 +++++++--- 5 files changed, 122 insertions(+), 29 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 786bb7e03..414c7bc95 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,20 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "type": "java", + "name": "TreeDemo", + "request": "launch", + "mainClass": "TreeDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "TreeTester", + "request": "launch", + "mainClass": "TreeTester", + "projectName": "data-structures_addf3fee" + }, { "type": "java", "name": "QueueTester", diff --git a/Chapter 17 Activities/CountLeaves/src/Tree.java b/Chapter 17 Activities/CountLeaves/src/Tree.java index 0853af2f7..65c43c3ae 100644 --- a/Chapter 17 Activities/CountLeaves/src/Tree.java +++ b/Chapter 17 Activities/CountLeaves/src/Tree.java @@ -24,6 +24,20 @@ public int size() for (Node child : children) { sum = sum + child.size(); } return 1 + sum; } + + public int leafCount() + { + + if (children.isEmpty()) { + return 1; + } else { + int count = 0; + for (Node child : children) { + count += child.leafCount(); + } + return count; + } + } } /** @@ -63,5 +77,15 @@ public int size() else { return root.size(); } } + public int leafCount() + { + if (root == null) { + return 0; + } else { + return root.leafCount(); + } + } + + // Additional methods will be added in later sections. } diff --git a/Chapter 17 Activities/CountNodesWithOneChild/src/BinaryTree.java b/Chapter 17 Activities/CountNodesWithOneChild/src/BinaryTree.java index b0bec272c..bd8230817 100644 --- a/Chapter 17 Activities/CountNodesWithOneChild/src/BinaryTree.java +++ b/Chapter 17 Activities/CountNodesWithOneChild/src/BinaryTree.java @@ -1,7 +1,4 @@ -//HIDE -/** - A binary tree in which each node has two children. -*/ +// BinaryTree.java public class BinaryTree { private Node root; @@ -34,15 +31,13 @@ public BinaryTree(Object rootData, BinaryTree left, BinaryTree right) root = new Node(); root.data = rootData; - if( left != null ) - { - root.left = left.root; - } + if (left != null) { + root.left = left.root; + } - if( right != null ) - { - root.right = right.root; - } + if (right != null) { + root.right = right.root; + } } class Node @@ -102,4 +97,33 @@ public BinaryTree right() result.root = root.right; return result; } + + /** + Counts the number of nodes with exactly one child. + @return the number of nodes with exactly one child + */ + public int countNodesWithOneChild() + { + return countNodesWithOneChild(root); + } + + /** + Helper method to count nodes with exactly one child. + @param node the current node in the tree + @return the number of nodes with exactly one child + */ + private int countNodesWithOneChild(Node node) + { + if (node == null) { + return 0; + } + + int count = 0; + + if ((node.left != null && node.right == null) || (node.left == null && node.right != null)) { + count = 1; + } + + return count + countNodesWithOneChild(node.left) + countNodesWithOneChild(node.right); + } } diff --git a/Chapter 17 Class Notes/src/BinaryTree.java b/Chapter 17 Class Notes/src/BinaryTree.java index 5877b6326..d03edbac6 100644 --- a/Chapter 17 Class Notes/src/BinaryTree.java +++ b/Chapter 17 Class Notes/src/BinaryTree.java @@ -10,7 +10,7 @@ public class BinaryTree */ public BinaryTree() { - + root = null; } /** @@ -19,7 +19,10 @@ public BinaryTree() */ public BinaryTree(Object rootData) { - + this.root = new Node(); + this.root.data = rootData; + this.root.left = null; + this.root.right = null; } /** @@ -30,12 +33,16 @@ public BinaryTree(Object rootData) */ public BinaryTree(Object rootData, BinaryTree left, BinaryTree right) { - + this(rootData); + this.root.left = left.root; + this.root.right = right.root; } static class Node { - + public Object data; + public Node left; + public Node right; } /** @@ -45,7 +52,13 @@ static class Node */ private static int height(Node n) { - return 0; + if (n == null) { + return 0; + } + else { + return 1 + Math.max(BinaryTree.height(n.left), BinaryTree.height(n.right)); + } + } /** @@ -54,7 +67,7 @@ private static int height(Node n) */ public int height() { - return 0; + return BinaryTree.height(this.root); } /** @@ -63,7 +76,7 @@ public int height() */ public boolean isEmpty() { - return false; + return this.root == null; } /** @@ -72,7 +85,7 @@ public boolean isEmpty() */ public Object data() { - return null; + return this.root.data; } /** @@ -81,7 +94,10 @@ public Object data() */ public BinaryTree left() { - return null; + BinaryTree subtree = new BinaryTree(); + subtree.root = this.root.left; + return subtree; + // return this.root.left <--- root.left is a Node, not a BinaryTree } /** @@ -90,6 +106,8 @@ public BinaryTree left() */ public BinaryTree right() { - return null; + BinaryTree subtree = new BinaryTree(); + subtree.root = this.root.right; + return subtree; } -} +} \ No newline at end of file diff --git a/Chapter 17 Class Notes/src/Tree.java b/Chapter 17 Class Notes/src/Tree.java index a856e4347..607e35105 100644 --- a/Chapter 17 Class Notes/src/Tree.java +++ b/Chapter 17 Class Notes/src/Tree.java @@ -6,10 +6,12 @@ */ public class Tree { + private Node root; static class Node { - + public Object data; + public List children; /** Computes the size of the subtree whose root is this node. @@ -17,7 +19,11 @@ static class Node */ public int size() { - return 0; + int total = 1; + for (Node child: this.children) { + total += child.size(); + } + return total; } } @@ -27,7 +33,9 @@ public int size() */ public Tree(Object rootData) { - + this.root = new Node(); + this.root.data = rootData; + this.root.children = new ArrayList<>(); } /** @@ -35,7 +43,7 @@ public Tree(Object rootData) */ public void addSubtree(Tree subtree) { - + this.root.children.add(subtree.root); } /** @@ -44,8 +52,13 @@ public void addSubtree(Tree subtree) */ public int size() { - return 0; + return this.root.size(); + } + + public String leafCount() { + // TODO Auto-generated method stub + throw new UnsupportedOperationException("Unimplemented method 'leafCount'"); } // Additional methods will be added in later sections. -} +} \ No newline at end of file From fe543366975915c0063432af2e50cfe7a5f59217 Mon Sep 17 00:00:00 2001 From: shriya Date: Fri, 7 Nov 2025 00:07:25 -0600 Subject: [PATCH 26/29] binary search trees and tree notes --- .../src/BinarySearchTree.java | 140 ++++++++++++++++-- Chapter 17 Class Notes/src/Tree.java | 41 ++++- 2 files changed, 167 insertions(+), 14 deletions(-) diff --git a/Chapter 17 Class Notes/src/BinarySearchTree.java b/Chapter 17 Class Notes/src/BinarySearchTree.java index 6720a3152..883221a19 100644 --- a/Chapter 17 Class Notes/src/BinarySearchTree.java +++ b/Chapter 17 Class Notes/src/BinarySearchTree.java @@ -12,7 +12,7 @@ public class BinarySearchTree */ public BinarySearchTree() { - + this.root = null; } /** @@ -21,7 +21,17 @@ public BinarySearchTree() */ public void add(Comparable obj) { - + Node newNode = new Node(); + newNode.data = obj; + newNode.left = null; + newNode.right = null; + + if (this.root == null) { + this.root = newNode; + } + else { + this.root.addNode(newNode); + } } /** @@ -31,6 +41,20 @@ public void add(Comparable obj) */ public boolean find(Comparable obj) { + Node current = this.root; + while (current != null) { + int diff = obj.compareTo(current.data); + if (diff == 0) { + return true; + } + else if (diff < 0) { + current = current.left; + } + else { + current = current.right; + } + } + return false; } @@ -41,7 +65,76 @@ public boolean find(Comparable obj) */ public void remove(Comparable obj) { - + Node toBeRemoved = this.root; + boolean found = false; + Node parent = null; + + while (!found && toBeRemoved != null) { + int diff = obj.compareTo(toBeRemoved.data); + if (diff == 0) { + found = true; + } + else if (diff < 0) { + parent = toBeRemoved; + toBeRemoved = toBeRemoved.left; + } + else { + parent = toBeRemoved; + toBeRemoved = toBeRemoved.right; + } + } + + if (!found) { + return; + } + + // Case 1 and Case 2 (At least one child is null) + if (toBeRemoved.left == null || toBeRemoved.right == null) { + Node newChild; + + if (toBeRemoved.left == null) { + newChild = toBeRemoved.right; + } + else { + newChild = toBeRemoved.left; + } + + // Remove the root if the parent is null + if (parent == null) { + this.root = newChild; + } + else if (parent.left == toBeRemoved) { + parent.left = newChild; + } + else { + parent.right = newChild; + } + + return; + } + + // Case 3: Remove a node with two children + + // Find the least element of the right subtree + // The least element will replace the removed node + Node leastParent = toBeRemoved; + Node least = toBeRemoved.right; + while (least.left != null) { + leastParent = least; + least = least.left; + } + + // Move the data to the node being removed + toBeRemoved.data = least.data; + + // Unlink the least child + if (leastParent == toBeRemoved) { + leastParent.right = least.right; + } + else { + leastParent.left = least.right; + } + } /** @@ -49,7 +142,9 @@ public void remove(Comparable obj) */ public void print() { - + // Print the tree using inorder traversal + print(this.root); + System.out.println(); } /** @@ -58,7 +153,13 @@ public void print() */ private static void print(Node parent) { - + if (parent == null) { + return; + } + + print(parent.left); + System.out.println(parent.data + " "); + print(parent.right); } /** @@ -67,7 +168,10 @@ private static void print(Node parent) */ static class Node { - + // A BST MUST BE made of Comparable Objects + public Comparable data; + public Node left; + public Node right; /** Inserts a new node as a descendant of this node. @@ -75,10 +179,26 @@ static class Node */ public void addNode(Node newNode) { + // If diff < 0, newNode is to the left of this node + // If diff > 0, newNode is to the right of this node + int diff = newNode.data.compareTo(data); + if (diff < 0) { + if (left == null) { + left = newNode; + } + else { + left.addNode(newNode); + } + } + else if (diff > 0) { + if (right == null) { + right = newNode; + } + else { + right.addNode(newNode); + } + } } } -} - - - +} \ No newline at end of file diff --git a/Chapter 17 Class Notes/src/Tree.java b/Chapter 17 Class Notes/src/Tree.java index 607e35105..6289ecb2e 100644 --- a/Chapter 17 Class Notes/src/Tree.java +++ b/Chapter 17 Class Notes/src/Tree.java @@ -55,10 +55,43 @@ public int size() return this.root.size(); } - public String leafCount() { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'leafCount'"); + // Additional methods will be added in later sections. + + /* + * A visitor method is called for each visited node + * during a tree traversal. + */ + public interface Visitor { + /* + * The visit method is called for each visited node. + * @param data: The data of the node being visited + */ + void visit(Object data); + } - // Additional methods will be added in later sections. + /* + * Traverse this tree in preorder. + * @param v: The visitor to be invoked on each node. + */ + public void preorder(Visitor v) { + Tree.preorder(this.root, v); + } + + /* + * Traverse the tree with a given root in preorder. + @param n: The root of the tree to traverse + @param v: The visitor to be invoked on each node + */ + private static void preorder(Node n, Visitor v) { + if (n == null) { + return; + } + + v.visit(n.data); + + for (Node child: n.children) { + Tree.preorder(child, v); + } + } } \ No newline at end of file From d38f331d24bca0ffb965b19a9980c4c9273b0605 Mon Sep 17 00:00:00 2001 From: shriya Date: Sun, 9 Nov 2025 22:19:57 -0600 Subject: [PATCH 27/29] depthfirst --- .vscode/launch.json | 7 ++++++ .../DepthFirst/src/Tree.java | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/.vscode/launch.json b/.vscode/launch.json index 414c7bc95..816a04449 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,13 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "type": "java", + "name": "DepthFirstTester", + "request": "launch", + "mainClass": "DepthFirstTester", + "projectName": "data-structures_addf3fee" + }, { "type": "java", "name": "TreeDemo", diff --git a/Chapter 17 Activities/DepthFirst/src/Tree.java b/Chapter 17 Activities/DepthFirst/src/Tree.java index 7842532b1..feee0f653 100644 --- a/Chapter 17 Activities/DepthFirst/src/Tree.java +++ b/Chapter 17 Activities/DepthFirst/src/Tree.java @@ -65,4 +65,26 @@ public int size() } // Additional methods will be added in later sections. + + public void depthFirst(Visitor v) + { + if (root == null) return; + depthFirst(root, v); + } + + + private boolean depthFirst(Node n, Visitor v) + { + if (n == null) return true; + + boolean continueTraversal = v.visit(n.data); + if (!continueTraversal) return false; + + for (Node child : n.children) + { + if (!depthFirst(child, v)) return false; + } + + return true; + } } From b03c3e110f388aa7392aff3d80a4d408c769a6a1 Mon Sep 17 00:00:00 2001 From: shriya Date: Sun, 9 Nov 2025 22:23:58 -0600 Subject: [PATCH 28/29] postorder method --- .../DepthFirst/src/DepthFirstTester.java | 3 +++ .../DepthFirst/src/Tree.java | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/Chapter 17 Activities/DepthFirst/src/DepthFirstTester.java b/Chapter 17 Activities/DepthFirst/src/DepthFirstTester.java index 6a28a67ae..8db1b6619 100644 --- a/Chapter 17 Activities/DepthFirst/src/DepthFirstTester.java +++ b/Chapter 17 Activities/DepthFirst/src/DepthFirstTester.java @@ -33,4 +33,7 @@ public static void main(String[] args) System.out.println("Expected: Anne Peter Sonia Mike Jane Sam Zara"); } + + + } diff --git a/Chapter 17 Activities/DepthFirst/src/Tree.java b/Chapter 17 Activities/DepthFirst/src/Tree.java index feee0f653..d75b29187 100644 --- a/Chapter 17 Activities/DepthFirst/src/Tree.java +++ b/Chapter 17 Activities/DepthFirst/src/Tree.java @@ -87,4 +87,25 @@ private boolean depthFirst(Node n, Visitor v) return true; } + + + public void postorder(Visitor v) + { + if (root == null) return; + postorder(root, v); + } + + + private boolean postorder(Node n, Visitor v) + { + if (n == null) return true; + + for (Node child : n.children) + { + if (!postorder(child, v)) return false; + } + + boolean continueTraversal = v.visit(n.data); + return continueTraversal; + } } From df33c1d89fc86e1952bec0d5a59f9afea72c4b92 Mon Sep 17 00:00:00 2001 From: shriya Date: Sat, 15 Nov 2025 19:51:20 -0600 Subject: [PATCH 29/29] sample website --- index.html | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 index.html diff --git a/index.html b/index.html new file mode 100644 index 000000000..cca103c11 --- /dev/null +++ b/index.html @@ -0,0 +1,23 @@ + + + + + + + +First Website + + + + + + Visit Weather Website + + + + + +