├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
└── java
│ └── rogeriogentil
│ └── data
│ └── structures
│ ├── chapter01
│ ├── Creativity.java
│ ├── CreditCard.java
│ ├── GameEntry.java
│ └── Reinforcement.java
│ ├── chapter03
│ ├── BiNode.java
│ ├── CircularyLinkedList.java
│ ├── DoublyLinkedList.java
│ ├── InsertionSort.java
│ ├── Node.java
│ ├── SinglyLinkedList.java
│ ├── StringToArray.java
│ └── reinforcement
│ │ ├── Exercise01.java
│ │ ├── Exercise02.java
│ │ ├── Exercise05.java
│ │ ├── Exercise06.java
│ │ └── PseudoRandom.java
│ ├── chapter05
│ ├── DiskUsage.java
│ ├── DrawnerBrazilianRuler.java
│ ├── Factorial.java
│ ├── RecursionBinarySearch.java
│ ├── RecursionFibonacci.java
│ ├── RecursionSumArrayElements.java
│ └── reinforcement
│ │ ├── Exercise01.java
│ │ ├── Exercise05.java
│ │ ├── Exercise07.java
│ │ ├── Exercise08.java
│ │ └── Exercise10.java
│ ├── chapter06
│ ├── ArrayCircularQueue.java
│ ├── ArrayStack.java
│ ├── ArrayUtil.java
│ ├── CircularQueue.java
│ ├── Deque.java
│ ├── DoublyLinkedList.java
│ ├── LinkedQueue.java
│ ├── LinkedStack.java
│ ├── MatchUtil.java
│ ├── Queue.java
│ ├── Stack.java
│ └── reinforcement
│ │ ├── Exercise01.txt
│ │ ├── Exercise02.txt
│ │ ├── Exercise03.txt
│ │ ├── Exercise04.java
│ │ ├── Exercise05.java
│ │ ├── Exercise07.txt
│ │ ├── Exercise08.txt
│ │ ├── Exercise09.txt
│ │ ├── Exercise10.java
│ │ └── Exercise12.txt
│ ├── chapter07
│ ├── ArrayList.java
│ ├── LinkedPositionalList.java
│ ├── List.java
│ ├── Position.java
│ ├── PositionalList.java
│ └── reinforcement
│ │ ├── Exercise01.txt
│ │ ├── Exercise02.java
│ │ ├── Exercise03.java
│ │ ├── Exercise05.java
│ │ └── Exercise10.java
│ ├── chapter08
│ ├── AbstractBinaryTree.java
│ ├── AbstractTree.java
│ ├── BinaryTree.java
│ ├── LinkedBinaryTree.java
│ ├── Tree.java
│ ├── TreeUtil.java
│ └── reinforcement
│ │ ├── Exercise01.txt
│ │ ├── Exercise05.java
│ │ ├── Exercise07.txt
│ │ ├── Exercise12.txt
│ │ ├── Exercise18.txt
│ │ ├── Exercise19.txt
│ │ ├── Exercise20.txt
│ │ ├── Exercise22.txt
│ │ └── Exercise24.txt
│ ├── chapter09
│ ├── AbstractPriorityQueue.java
│ ├── AdaptablePriorityQueue.java
│ ├── DefaultComparator.java
│ ├── Entry.java
│ ├── HeapAdaptablePriorityQueue.java
│ ├── HeapPriorityQueue.java
│ ├── PriorityQueue.java
│ ├── PriorityQueueUtils.java
│ ├── SortedPriorityQueue.java
│ ├── StringLengthComparator.java
│ ├── UnsortedProrityQueue.java
│ └── reinforcement
│ │ ├── Exercise02.txt
│ │ ├── Exercise03.txt
│ │ ├── Exercise07.txt
│ │ ├── Exercise08.txt
│ │ ├── Exercise17.txt
│ │ └── Exercise19.txt
│ ├── chapter10
│ ├── AbstractMap.java
│ ├── AbstractSortedMap.java
│ ├── Map.java
│ ├── SortedMap.java
│ └── UnsortedTableMap.java
│ ├── chapter11
│ ├── AVLTreeMap.java
│ ├── RBTreeMap.java
│ ├── SplayTreeMap.java
│ ├── TreeMap.java
│ └── reinforcement
│ │ ├── Exercise01.txt
│ │ ├── Exercise02.txt
│ │ ├── Exercise03.txt
│ │ ├── Exercise04.txt
│ │ ├── Exercise05.txt
│ │ ├── Exercise08.txt
│ │ ├── Exercise09.txt
│ │ ├── Exercise14.txt
│ │ ├── Exercise15.txt
│ │ └── Exercise17.txt
│ ├── chapter12
│ ├── MergeSort.java
│ ├── QuickSort.java
│ └── reinforcement
│ │ ├── Exercise01.txt
│ │ ├── Exercise02.txt
│ │ ├── Exercise04.txt
│ │ └── Exercise05.txt
│ └── chapter14
│ ├── AdjacencyMapGraph.java
│ ├── Edge.java
│ ├── Graph.java
│ ├── GraphTraversals.java
│ ├── Vertex.java
│ └── reinforcement
│ ├── Exercise05.txt
│ ├── Exercise06.txt
│ ├── Exercise07.txt
│ ├── Exercise08.txt
│ ├── Exercise11.txt
│ └── Exercise13.txt
└── test
└── java
└── rogeriogentil
└── data
└── structures
├── chapter03
├── ArraysTest.java
├── CircularyLinkedListTest.java
├── DoublyLinkedListTest.java
├── InsertionSortTest.java
└── SinglyLinkedListTest.java
├── chapter05
├── FactorialTest.java
├── RecursionBinarySearchTest.java
└── RecursionFibonacciTest.java
├── chapter06
├── ArrayCircularQueueTest.java
├── ArrayStackTest.java
├── ArrayUtilTest.java
├── MatchUtilTest.java
└── reinforcement
│ ├── Exercise04Test.java
│ ├── Exercise05Test.java
│ └── Exercise10Test.java
├── chapter07
├── ArrayListTest.java
└── reinforcement
│ ├── Exercise02Test.java
│ ├── Exercise03Test.java
│ └── Exercise10Test.java
├── chapter08
├── TreeUtilTest.java
└── reinforcement
│ └── Exercise05Test.java
├── chapter09
├── StringLengthComparatorTest.java
└── UnsortedProrityQueueTest.java
└── chapter12
├── MergeSortTest.java
└── QuickSortTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.ear
17 | *.zip
18 | *.tar.gz
19 | *.rar
20 |
21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
22 | hs_err_pid*
23 |
24 | # Maven compiled files folder
25 | target/
26 |
27 | # Netbeans IDE folders and files
28 | nb-configuration.xml
29 | nbactions.xml
30 | nbproject/
31 |
32 | # Eclipse IDE files and folders
33 | .classpath
34 | .project
35 | .settings/
36 |
37 | # IntelliJ IDEA files and folders
38 | .idea/
39 | *.iml
40 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | notifications:
3 | email:
4 | - rogerio_gentil@yahoo.com.br
5 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # data-structures-and-algorithms
2 | Codes and resolutions of the exercises of Goodrich, Tamassia & Goldwasser's Data Structures & Algorithms in Java Sixth Edition Book (2014).
3 |
4 | ## Status
5 | [](https://travis-ci.org/rogeriogentil/data-structures-and-algorithms)
6 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | rogeriogentil
8 | data-structures-and-algorithms
9 | 1.0.0-SNAPSHOT
10 | jar
11 |
12 | Data Structures and Algorithms in Java
13 | Codes and resolutions of the exercises of Goorich, Tamassia And Godwasser's Data Structures and Algorithms in Java Sixth Edition Book
14 | 2017
15 |
16 |
17 | UTF-8
18 | 1.8
19 | 1.8
20 |
21 |
22 |
23 |
24 | junit
25 | junit
26 | 4.12
27 | test
28 |
29 |
30 | org.hamcrest
31 | hamcrest-core
32 |
33 |
34 |
35 |
36 |
37 | org.hamcrest
38 | hamcrest-library
39 | 1.3
40 | test
41 |
42 |
43 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter01/Creativity.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter01;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class Creativity {
8 |
9 | public static void main(String[] args) {
10 | Creativity creativity = new Creativity();
11 |
12 | // C-1.14
13 | int[] integers = {0, 2, 4, 6, 8};
14 | int[] reverse = creativity.reverse(integers);
15 |
16 | System.out.print("{");
17 | for(Integer i : reverse) {
18 | System.out.print(i + ", ");
19 | }
20 | System.out.println("}");
21 |
22 | // C-1.15
23 | int smallest = creativity.smallest(integers);
24 | System.out.println("Smallest = " + smallest);
25 |
26 | int smallest2 = creativity.smallest(new int[5]);
27 | System.out.println("Smallest = " + smallest2);
28 |
29 | int[] ints = {-3, -1, 0, 1, 3};
30 | int smallest3 = creativity.smallest(ints);
31 | System.out.println("Smallest = " + smallest3);
32 | }
33 |
34 | /**
35 | * C-1.14
36 | */
37 | public int[] reverse(int[] array) {
38 | int[] reverse = new int[array.length];
39 |
40 | int j = 0;
41 | for (int i = array.length - 1; i > 0; i--) {
42 | reverse[j++] = array[i];
43 | }
44 |
45 | return reverse;
46 | }
47 |
48 | /**
49 | * C-1.15
50 | */
51 | public int smallest(int[] array) {
52 | int smallest = array[0];
53 |
54 | for (int i = 1; i < array.length; i++) {
55 | if (array[i] < smallest) {
56 | smallest = array[i];
57 | }
58 | }
59 |
60 | return smallest;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter01/CreditCard.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter01;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class CreditCard {
8 |
9 | private String customer;
10 | private String bank;
11 | private String account;
12 | private int limit;
13 | protected double balance;
14 |
15 | public CreditCard(String customer, String bank, String account, int limit, double balance) {
16 | this.customer = customer;
17 | this.bank = bank;
18 | this.account = account;
19 | this.limit = limit;
20 | this.balance = balance;
21 | }
22 |
23 | public CreditCard(String customer, String bank, String account, int limit) {
24 | this(customer, bank, account, limit, 0.0);
25 | }
26 |
27 | public String getCustomer() {
28 | return customer;
29 | }
30 |
31 | public String getBank() {
32 | return bank;
33 | }
34 |
35 | public String getAccount() {
36 | return account;
37 | }
38 |
39 | public int getLimit() {
40 | return limit;
41 | }
42 |
43 | public double getBalance() {
44 | return balance;
45 | }
46 |
47 | public boolean charge(double price) {
48 | if (price + balance > limit)
49 | return false;
50 |
51 | balance += price;
52 | return true;
53 | }
54 |
55 | public void makePayment(double amount) {
56 | // R-1.12
57 | if (amount < 0) return;
58 | balance -= amount;
59 | }
60 |
61 | // R-1.11
62 | public void updateLimit(int newLimit) {
63 | this.limit = newLimit;
64 | }
65 |
66 | public static void printSummary(CreditCard card) {
67 | System.out.println("-------------------------------------");
68 | System.out.println("Customer = " + card.customer);
69 | System.out.println("Bank = " + card.bank);
70 | System.out.println("Account = " + card.account);
71 | System.out.println("Balance = " + card.balance);
72 | System.out.println("Limit = " + card.limit);
73 | System.out.println("-------------------------------------");
74 | }
75 |
76 | public static void main(String[ ] args) {
77 | CreditCard[ ] wallet = new CreditCard[3];
78 | wallet[0] = new CreditCard("John Bowman", "California Savings", "5391 0375 9387 5309", 5000);
79 | wallet[1] = new CreditCard("John Bowman", "California Federal", "3485 0399 3395 1954", 3500);
80 | wallet[2] = new CreditCard("John Bowman", "California Finance", "5391 0375 9387 5309", 2500, 300);
81 |
82 | for (int val = 1; val <= 16; val++) {
83 | wallet[0].charge(3*val);
84 | wallet[1].charge(3*val);//wallet[1].charge(2*val);
85 | wallet[2].charge(3*val);//wallet[2].charge(val);
86 | }
87 |
88 | for (CreditCard card : wallet) {
89 | CreditCard.printSummary(card);
90 | while (card.getBalance( ) > 200.0) {
91 | card.makePayment(200);
92 | System.out.println("New balance = " + card.getBalance());
93 | }
94 | }
95 |
96 | // R-1.11
97 | for (int i = 0; i < wallet.length; i++) {
98 | System.out.println("Old limit on wallet[" + i + "] = " + wallet[i].limit);
99 |
100 | int newLimit = wallet[i].limit * 2;
101 | wallet[i].updateLimit(newLimit);
102 |
103 | System.out.println("New limit on wallet[" + i + "] = " + wallet[i].limit);
104 | }
105 |
106 | // R-1.12
107 | for (CreditCard card : wallet) {
108 | card.makePayment(-100);
109 | System.out.println("New balance = " + card.getBalance());
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter01/GameEntry.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter01;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class GameEntry implements Cloneable {
8 |
9 | public int score;
10 |
11 | public GameEntry(int score) {
12 | this.score = score;
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter01/Reinforcement.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter01;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class Reinforcement {
8 |
9 | public static void main(String[] args) {
10 | Reinforcement r = new Reinforcement();
11 |
12 | // R-1.3
13 | System.out.println(r.isMultiple(2, 6));
14 | System.out.println(r.isMultiple(3, 6));
15 | System.out.println(r.isMultiple(4, 9));
16 |
17 | // R-1.5
18 | System.out.println("R-1.5");
19 | System.out.println(r.sumInts(3));
20 | System.out.println(r.sumInts(5));
21 | // System.out.println(r.sumInts(-1));
22 |
23 | // R-1.6
24 | System.out.println("R-1.6");
25 | System.out.println(r.sumOdds(3));
26 | System.out.println(r.sumOdds(4));
27 | System.out.println(r.sumOdds(5));
28 |
29 | // R-1.7
30 | System.out.println("R-1.7");
31 | System.out.println(r.sumSquaers(2));
32 | System.out.println(r.sumSquaers(3));
33 |
34 | // R-1.8
35 | System.out.println("R-1.8");
36 | System.out.println(r.countVowels(""));
37 | System.out.println(r.countVowels("aeiou"));
38 | System.out.println(r.countVowels("Rogerio"));
39 | System.out.println(r.countVowels("PAULA"));
40 |
41 | }
42 |
43 | /**
44 | * R-1.3
45 | *
46 | * @param n
47 | * @param m
48 | * @return
49 | */
50 | public boolean isMultiple(long n, long m) {
51 | return m % n == 0;
52 | }
53 |
54 | /**
55 | * R-1.4 - This method cannot use the multiplication, modulus, or division operators.
56 | */
57 | public boolean isEven(int i) {
58 | return false;
59 | }
60 |
61 | /**
62 | * R-1.5 Write a short Java method that takes an integer n and returns the sum of all positive integers less than or
63 | * equal to n.
64 | */
65 | public long sumInts(int n) {
66 | if (n < 0) {
67 | throw new RuntimeException("Não é possível somar números negativos.");
68 | }
69 |
70 | long sum = 0;
71 | for (int i = n; i > 0; --i) {
72 | sum += i;
73 | }
74 |
75 | return sum;
76 | }
77 |
78 | /**
79 | * R-1.6 Write a short Java method that takes an integer n and returns the sum of all the odd positive integers less
80 | * than or equal to n.
81 | */
82 | public long sumOdds(int n) {
83 | if (n < 0) {
84 | throw new RuntimeException("Não é possível somar números negativos.");
85 | }
86 |
87 | long sum = 0;
88 | for (int i = n; i > 0; --i) {
89 | if (i % 2 == 1) {
90 | sum += i;
91 | }
92 | }
93 |
94 | return sum;
95 | }
96 |
97 | /**
98 | * R-1.7 Write a short Java method that takes an integer n and returns the sum of the squares of all positive
99 | * integers less than or equal to n.
100 | */
101 | public long sumSquaers(int n) {
102 | if (n < 0) {
103 | throw new RuntimeException("Não é possível somar números negativos.");
104 | }
105 |
106 | long sum = 0;
107 | for (int i = n; i > 0; --i) {
108 | sum += i * i;
109 | }
110 |
111 | return sum;
112 | }
113 |
114 | /**
115 | * R-1.8 Write a short Java method that counts the number of vowels in a given character string.
116 | */
117 | public int countVowels(String s) {
118 | int count = 0;
119 | String sl = s.toLowerCase();
120 |
121 | for (int i = 0; i < s.length(); i++) {
122 | char c = sl.charAt(i);
123 | switch(c) {
124 | case 'a': count++; break;
125 | case 'e': count++; break;
126 | case 'i': count++; break;
127 | case 'o': count++; break;
128 | case 'u': count++; break;
129 | }
130 | }
131 |
132 | return count;
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/BiNode.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | * @param
7 | */
8 | public class BiNode {
9 |
10 | private BiNode previous;
11 | private E element;
12 | private BiNode next;
13 |
14 | public BiNode() {
15 | }
16 |
17 | public BiNode(E element) {
18 | this.element = element;
19 | }
20 |
21 | public BiNode getPrevious() {
22 | return previous;
23 | }
24 |
25 | public void setPrevious(BiNode previous) {
26 | this.previous = previous;
27 | }
28 |
29 | public E getElement() {
30 | return element;
31 | }
32 |
33 | public void setElement(E element) {
34 | this.element = element;
35 | }
36 |
37 | public BiNode getNext() {
38 | return next;
39 | }
40 |
41 | public void setNext(BiNode next) {
42 | this.next = next;
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/CircularyLinkedList.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | * @param
7 | */
8 | public class CircularyLinkedList {
9 |
10 | private int size;
11 | private Node tailNode;
12 |
13 | public int getSize() {
14 | return size;
15 | }
16 |
17 | public Node getHeadNode() {
18 | return tailNode.getNext();
19 | }
20 |
21 | public Node getTailNode() {
22 | return tailNode;
23 | }
24 |
25 | public boolean isEmpty() {
26 | return size == 0;
27 | }
28 |
29 | public E first() {
30 | if (this.isEmpty())
31 | return null;
32 |
33 | return getTailNode().getNext().getElement();
34 | }
35 |
36 | public E last() {
37 | if (this.isEmpty())
38 | return null;
39 |
40 | return getTailNode().getNext().getElement();
41 | }
42 |
43 | public void addFirst(E element) {
44 | Node newest = new Node<>(element);
45 |
46 | if (isEmpty()) {
47 | tailNode = newest;
48 | } else {
49 | newest.setNext(tailNode.getNext());
50 | }
51 |
52 | tailNode.setNext(newest);
53 |
54 | size++;
55 | }
56 |
57 | public void addLast(E element) {
58 | Node newest = new Node<>(element);
59 |
60 | if (this.isEmpty()) {
61 | tailNode = newest;
62 | tailNode.setNext(newest);
63 | newest.setNext(tailNode);
64 | } else {
65 | newest.setNext(tailNode.getNext());
66 | tailNode.setNext(newest);
67 | tailNode = newest;
68 | }
69 |
70 | size++;
71 | }
72 |
73 | public void rotate() {
74 | if (!isEmpty()) {
75 | tailNode = tailNode.getNext();
76 | }
77 | }
78 | }
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/DoublyLinkedList.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | * @param
7 | */
8 | public class DoublyLinkedList {
9 |
10 | private int size;
11 | private BiNode header;
12 | private BiNode trailer;
13 |
14 | public DoublyLinkedList() {
15 | header = new BiNode<>();
16 | trailer = new BiNode<>();
17 |
18 | header.setNext(trailer);
19 | trailer.setPrevious(header);
20 | }
21 |
22 | public int getSize() {
23 | return size;
24 | }
25 |
26 | public BiNode getHeader() {
27 | return header;
28 | }
29 |
30 | public BiNode getTrailer() {
31 | return trailer;
32 | }
33 |
34 | public boolean isEmpty() {
35 | return this.size == 0;
36 | }
37 |
38 | public void addFirst(E element) {
39 | BiNode node = new BiNode<>(element);
40 | node.setPrevious(header);
41 | node.setNext(header.getNext());
42 |
43 | header.getNext().setPrevious(node);
44 | header.setNext(node);
45 |
46 | size++;
47 | }
48 |
49 | public E first() {
50 | return this.header.getNext().getElement();
51 | }
52 |
53 | public void addLast(E element) {
54 | BiNode node = new BiNode<>(element);
55 | node.setPrevious(trailer.getPrevious());
56 | node.setNext(trailer);
57 |
58 | trailer.getPrevious().setNext(node);
59 | trailer.setPrevious(node);
60 | size++;
61 | }
62 |
63 | public E last() {
64 | return trailer.getPrevious().getElement();
65 | }
66 |
67 | public void removeFirst() {
68 | if (isEmpty()) return;
69 |
70 | header.setNext(header.getNext().getNext());
71 | header.getNext().getNext().setPrevious(header);
72 | size--;
73 | }
74 |
75 | public void removeLast() {
76 | if (isEmpty()) return;
77 |
78 | trailer.setPrevious(trailer.getPrevious().getPrevious());
79 | trailer.getPrevious().getPrevious().setNext(trailer);
80 | size--;
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/InsertionSort.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class InsertionSort {
8 |
9 | public Integer[] sort(Integer[] array) {
10 |
11 | for (int i = 1; i < array.length; i++) {
12 | int valorAtual = array[i];
13 | int j = i;
14 |
15 | while (j > 0 && valorAtual < array[j - 1]) {
16 | array[j] = array[j -1];
17 | j--;
18 | }
19 |
20 | array[j] = valorAtual;
21 | }
22 |
23 | return array;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/Node.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class Node {
8 |
9 | private E element;
10 | private Node next;
11 |
12 | public Node() {
13 | }
14 |
15 | public Node(E element) {
16 | this.element = element;
17 | }
18 |
19 | public E getElement() {
20 | return element;
21 | }
22 |
23 | public void setElement(E element) {
24 | this.element = element;
25 | }
26 |
27 | public Node getNext() {
28 | return next;
29 | }
30 |
31 | public void setNext(Node next) {
32 | this.next = next;
33 | }
34 | }
35 |
36 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/SinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class SinglyLinkedList {
8 |
9 | private int size;
10 | private Node headNode;
11 | private Node tailNode;
12 |
13 | public Node getHead() {
14 | return headNode;
15 | }
16 |
17 | public Node getTail() {
18 | return tailNode;
19 | }
20 |
21 | public int getSize() {
22 | return size;
23 | }
24 |
25 | public void addFirst(E element) {
26 | Node newest = new Node(element);
27 | newest.setNext(headNode);
28 | headNode = newest;
29 |
30 | if (this.isEmpty()) {
31 | tailNode = headNode;
32 | }
33 |
34 | size++;
35 | }
36 |
37 | public void addLast(E element) {
38 | Node newest = new Node(element);
39 |
40 | if (this.isEmpty()) {
41 | headNode = newest;
42 | tailNode = headNode;
43 | } else {
44 | tailNode.setNext(newest);
45 | tailNode = newest;
46 | }
47 |
48 | size++;
49 | }
50 |
51 | public E removeFist() {
52 | if (this.isEmpty()) {
53 | return null;
54 | }
55 |
56 | E element = headNode.getElement();
57 | headNode = headNode.getNext();
58 | // headNode.setNext(null);
59 | size--;
60 |
61 | return element;
62 | }
63 |
64 | public boolean isEmpty() {
65 | return this.size == 0;
66 | }
67 |
68 | public E first() {
69 | return headNode.getElement();
70 | }
71 | }
72 |
73 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/StringToArray.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class StringToArray {
8 |
9 | public static void main(String[] args) {
10 | String bird = "black bird";
11 | char[] characters = bird.toCharArray();
12 |
13 | for (int i = 0; i < characters.length; i++) {
14 | System.out.println("c[" + i + "]: " + characters[i]);
15 | }
16 |
17 | String newBird = new String(characters);
18 | System.out.println(newBird);
19 |
20 | char t = 'T';
21 | System.out.println(t);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/reinforcement/Exercise01.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03.reinforcement;
2 |
3 | /**
4 | * Give the next five pseudorandom numbers generated by the process described on
5 | * page 113:
6 | *
7 | * next = (a ∗ cur + b) % n;
8 | *
9 | * , with a = 12, b = 5, and n = 100, and 92 as the seed for cur.
10 | *
11 | * @author Rogerio J. Gentil
12 | */
13 | public class Exercise01 {
14 |
15 | public static void main(String[] args) {
16 | int seed = 92;
17 |
18 | PseudoRandom pseudoRandom = new PseudoRandom(seed);
19 | double first = pseudoRandom.next();
20 | double second = pseudoRandom.next();
21 | double third = pseudoRandom.next();
22 | double fourth = pseudoRandom.next();
23 | double fifth = pseudoRandom.next();
24 |
25 | System.out.println("1º: " + first);
26 | System.out.println("2º: " + second);
27 | System.out.println("3º: " + third);
28 | System.out.println("4º: " + fourth);
29 | System.out.println("5º: " + fifth);
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/reinforcement/Exercise02.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03.reinforcement;
2 |
3 | import java.util.Date;
4 | import java.util.Random;
5 |
6 | /**
7 | * Write a Java method that repeatedly selects and removes a random entry from
8 | * an array until the array holds no more entries.
9 | *
10 | * @author Rogerio J. Gentil
11 | */
12 | public class Exercise02 {
13 |
14 | private static int capacidade = 20;
15 | private static Double[] doubleArray = new Double[capacidade];
16 |
17 | public static void main(String[] args) {
18 | PseudoRandom pseudoRandom = new PseudoRandom(new Date().getTime());
19 |
20 | for (int i = 0; i < capacidade; i++) {
21 | doubleArray[i] = pseudoRandom.next();
22 | System.out.println(i + ". " + doubleArray[i]);
23 | }
24 |
25 | while (doubleArray.length > 0) { // Testar todas as entradas == null ou total de elemento == 0?
26 | remove();
27 | }
28 | }
29 |
30 | public static void remove() {
31 | Random random = new Random();
32 | int index = random.nextInt(capacidade);
33 |
34 | if (doubleArray[index] == null) {
35 | return;
36 | }
37 |
38 | double valor = doubleArray[index];
39 | doubleArray[index] = null;
40 |
41 | System.out.println("removeu no index " + index + ": " + valor);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/reinforcement/Exercise05.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03.reinforcement;
2 |
3 | /**
4 | * Ver método remofirst();
5 | *
6 | * @author rogerio
7 | */
8 | public class Exercise05 {
9 |
10 | private class SinglyLinkedList {
11 |
12 | private int size;
13 | private Node headNode;
14 | private Node tailNode;
15 |
16 | public Node getHead() {
17 | return headNode;
18 | }
19 |
20 | public Node getTail() {
21 | return tailNode;
22 | }
23 |
24 | public int getSize() {
25 | return size;
26 | }
27 |
28 | public void addFirst(E element) {
29 | Node newest = new Node(element);
30 | newest.setNext(headNode);
31 | headNode = newest;
32 |
33 | if (this.isEmpty()) {
34 | tailNode = headNode;
35 | }
36 |
37 | size++;
38 | }
39 |
40 | public void addLast(E element) {
41 | Node newest = new Node(element);
42 |
43 | if (this.isEmpty()) {
44 | headNode = newest;
45 | tailNode = headNode;
46 | } else {
47 | tailNode.setNext(newest);
48 | tailNode = newest;
49 | }
50 |
51 | size++;
52 | }
53 |
54 | public E removeFirst() { // removes and returns the first element
55 | if (isEmpty()) {
56 | return null; // nothing to remove
57 | }
58 | E answer = headNode.getElement();
59 | headNode = headNode.getNext(); // will become null if list had only one node
60 | size--;
61 |
62 | /*
63 | What are the consequences if we were to remove those two lines from the
64 | code? Explain why the class would or would not work with such a modification.
65 |
66 | R: Caso essas duas próximas linhas fosse removidas, quando se removesse
67 | o primeiro elemento de um lista com apenas 1 elemento o ponteiro ponteiro
68 | do 'tail' ainda permaneceria ligado ao objeto do elemento a ser removido.
69 | Logo, o GC não recolheria o objeto apontado para 'tail'.
70 | */
71 | if (size == 0) {
72 | tailNode = null; // special case as list is now empty
73 | }
74 | return answer;
75 | }
76 |
77 | public boolean isEmpty() {
78 | return this.size == 0;
79 | }
80 | }
81 |
82 | private class Node {
83 |
84 | private E element;
85 | private Node next;
86 |
87 | public Node() {
88 | }
89 |
90 | public Node(E element) {
91 | this.element = element;
92 | }
93 |
94 | public E getElement() {
95 | return element;
96 | }
97 |
98 | public void setElement(E element) {
99 | this.element = element;
100 | }
101 |
102 | public Node getNext() {
103 | return next;
104 | }
105 |
106 | public void setNext(Node next) {
107 | this.next = next;
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/reinforcement/Exercise06.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03.reinforcement;
2 |
3 | /**
4 | * @author rogerio
5 | */
6 | public class Exercise06 {
7 |
8 | private class SinglyLinkedList {
9 |
10 | private int size;
11 | private Node headNode;
12 | private Node tailNode;
13 |
14 | public Node getHead() {
15 | return headNode;
16 | }
17 |
18 | public Node getTail() {
19 | return tailNode;
20 | }
21 |
22 | public int getSize() {
23 | return size;
24 | }
25 |
26 | public void addFirst(E element) {
27 | Node newest = new Node(element);
28 | newest.setNext(headNode);
29 | headNode = newest;
30 |
31 | if (this.isEmpty()) {
32 | tailNode = headNode;
33 | }
34 |
35 | size++;
36 | }
37 |
38 | public void addLast(E element) {
39 | Node newest = new Node(element);
40 |
41 | if (this.isEmpty()) {
42 | headNode = newest;
43 | tailNode = headNode;
44 | } else {
45 | tailNode.setNext(newest);
46 | tailNode = newest;
47 | }
48 |
49 | size++;
50 | }
51 |
52 | public void removeFist() {
53 | if (this.isEmpty()) {
54 | return;
55 | }
56 | headNode = headNode.getNext();
57 | headNode.setNext(null);
58 | size--;
59 | }
60 |
61 | public E removeFirst() { // removes and returns the first element
62 | if (isEmpty()) {
63 | return null; // nothing to remove
64 | }
65 | E answer = headNode.getElement();
66 | headNode = headNode.getNext(); // will become null if list had only one node
67 | size--;
68 |
69 | if (size == 0) {
70 | tailNode = null; // special case as list is now empty
71 | }
72 | return answer;
73 | }
74 |
75 | public boolean isEmpty() {
76 | return this.size == 0;
77 | }
78 | }
79 |
80 | private class Node {
81 |
82 | private E element;
83 | private Node next;
84 |
85 | public Node() {
86 | }
87 |
88 | public Node(E element) {
89 | this.element = element;
90 | }
91 |
92 | public E getElement() {
93 | return element;
94 | }
95 |
96 | public void setElement(E element) {
97 | this.element = element;
98 | }
99 |
100 | public Node getNext() {
101 | return next;
102 | }
103 |
104 | public void setNext(Node next) {
105 | this.next = next;
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter03/reinforcement/PseudoRandom.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter03.reinforcement;
2 |
3 | /**
4 | *
5 | * @author Rogerio J. Gentil
6 | */
7 | public class PseudoRandom {
8 |
9 | private double current;
10 | private final int a = 12;
11 | private final int b = 5;
12 | private final int n = 100;
13 |
14 | public PseudoRandom(long seed) {
15 | this.current = seed;
16 | }
17 |
18 | public double next() {
19 | double next = (a * current + b) % n;
20 | this.current = next;
21 | return next;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/DiskUsage.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05;
2 |
3 | import java.io.File;
4 |
5 | /**
6 | *
7 | * @author rogerio
8 | */
9 | public class DiskUsage {
10 |
11 | public static long analysis(File path) {
12 | // System.out.println("File or directory: " + path.getName());
13 |
14 | long total = path.length();
15 |
16 | if (path.isDirectory()) {
17 | for (File file : path.listFiles()) {
18 | total += analysis(file);
19 | }
20 | }
21 |
22 | System.out.println(total + "\t" + path);
23 | return total;
24 | }
25 |
26 | public static void main(String[] args) {
27 | String path = "/home/rogerio/tmp";
28 | File file = new File(path);
29 |
30 | System.out.println("Disk usage in " + path + ": " + analysis(file) + " bytes");
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/DrawnerBrazilianRuler.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class DrawnerBrazilianRuler {
8 |
9 | public static void drawRuler(int nroCentimetros, int majorLenth) {
10 | drawLine(majorLenth, 0);
11 | for (int j = 1; j <= nroCentimetros; j++) {
12 | drawInterval(majorLenth - 1);
13 | drawLine(majorLenth, j);
14 | }
15 | }
16 |
17 | public static void drawInterval(int centralLength) {
18 | if (centralLength >= 1) {
19 | drawInterval(centralLength - 1);
20 | drawLine(centralLength);
21 | drawInterval(centralLength - 1);
22 | }
23 | }
24 |
25 | public static void drawLine(int tickLength) {
26 | drawLine(tickLength, - 1);
27 | }
28 |
29 | public static void drawLine(int tickLength, int tickLabel) {
30 | for (int j = 0; j < tickLength; j++) {
31 | System.out.print("-");
32 | }
33 |
34 | if (tickLabel >= 0) {
35 | System.out.print(" " + tickLabel);
36 | }
37 |
38 | System.out.print("\n");
39 | }
40 |
41 | public static void main(String[] args) {
42 | DrawnerBrazilianRuler.drawRuler(5, 3);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/Factorial.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class Factorial {
8 |
9 | public static long factorial(int n) {
10 | if (n <= 0)
11 | return 1;
12 |
13 | return n * factorial(n - 1);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/RecursionBinarySearch.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class RecursionBinarySearch {
8 |
9 | public static int search(int n, int[] array, int indexLowest, int indexHighest) {
10 | if (indexLowest > indexHighest) {
11 | return -1;
12 | }
13 |
14 | int middle = (indexHighest + indexLowest) / 2;
15 | int number = array[middle];
16 |
17 | if (n == number) {
18 | return middle;
19 | }
20 |
21 | if (n < number) {
22 | return search(n, array, indexLowest, middle - 1);
23 | } else {
24 | return search(n, array, middle + 1, indexHighest);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/RecursionFibonacci.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class RecursionFibonacci {
8 |
9 | public static int get(int thElement) {
10 | if (thElement <= 1) {
11 | return 1;
12 | } else {
13 | return get(thElement - 1) + get(thElement - 2);
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/RecursionSumArrayElements.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class RecursionSumArrayElements {
8 |
9 | public static int sum(int[] array, int index) {
10 | int total = 0;
11 |
12 | if (array.length == 0 || index == array.length - 1) {
13 | return total;
14 | }
15 |
16 | return total + sum(array, index + 1);
17 | }
18 |
19 | public static void main(String[] args) {
20 | int[] array = {2, 1, 3, 5};
21 | int total = sum(array, 0);
22 | System.out.println("Total: " + total);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/reinforcement/Exercise01.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05.reinforcement;
2 |
3 | /**
4 | * Describe a recursive algorithm for finding the maximum element in an array, A, of n elements.
5 | * What is your running time and space usage?
6 | *
7 | * @author rogerio
8 | */
9 | public class Exercise01 {
10 |
11 | public int maximumElement(int[] A, int index) {
12 | if (A.length == 1) {
13 | return A[0];
14 | }
15 |
16 | if (A[index] > A[index + 1]) {
17 | return A[index];
18 | }
19 |
20 | return maximumElement(A, index + 1);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/reinforcement/Exercise05.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05.reinforcement;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class Exercise05 {
8 |
9 | public static int[] reverseArray(int[] array, int beginIndex, int endIndex) {
10 | if (beginIndex > endIndex) {
11 | return array;
12 | }
13 |
14 | int aux = array[beginIndex];
15 | array[beginIndex] = array[endIndex];
16 | array[endIndex] = aux;
17 |
18 | return reverseArray(array, beginIndex + 1, endIndex - 1);
19 | }
20 |
21 | public static void main(String[] args) {
22 | int[] data = {4, 3, 6, 2, 6};
23 | int[] dataReverse = reverseArray(data, 0, 4);
24 |
25 | for (int i = 0; i < dataReverse.length; i++) {
26 | System.out.print(dataReverse[i] + " ");
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/reinforcement/Exercise07.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05.reinforcement;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class Exercise07 {
8 |
9 | /**
10 | * Somatória 1/k, k = 1 até n
11 | *
12 | * ex: 1 + 1/2 + 1/3 + 1/4 + ...
13 | *
14 | * @return
15 | */
16 | public static double getNthHarmonicNumber(int nth) {
17 | if (nth < 1) {
18 | throw new IllegalArgumentException("Parâmetro não pode ser menor que 1");
19 | }
20 |
21 | if (nth == 1)
22 | return 1;
23 |
24 | return (double) 1 / nth + getNthHarmonicNumber(nth - 1);
25 | }
26 |
27 | public static void main(String[] args) {
28 | double n = getNthHarmonicNumber(2);
29 | System.out.println("n = " + n);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/reinforcement/Exercise08.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05.reinforcement;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class Exercise08 {
8 |
9 | public static int toInt(String s) {
10 | char[] array = s.toCharArray();
11 |
12 | return 10498;
13 | }
14 |
15 | public static void main(String[] args) {
16 | String numero = "010498";
17 | Integer n = toInt(numero);
18 | System.out.println("n é inteiro? " + (n instanceof Integer));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter05/reinforcement/Exercise10.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter05.reinforcement;
2 |
3 | /**
4 | * Describe a way to use recursion to compute the sum of all the elements in an n × n (two-dimensional) array of integers.
5 | *
6 | * @author rogerio
7 | */
8 | public class Exercise10 {
9 |
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/ArrayCircularQueue.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class ArrayCircularQueue implements Queue {
8 |
9 | private static final int CAPACITY = 1000;
10 | private int front;
11 | private int storedSize;
12 | private E[] array;
13 |
14 | public ArrayCircularQueue() {
15 | this(CAPACITY);
16 | }
17 |
18 | public ArrayCircularQueue(final int capacity) {
19 | array = (E[]) new Object[capacity];
20 | }
21 |
22 | @Override
23 | public void enqueue(E element) {
24 | if (this.storedSize == this.array.length) {
25 | throw new IllegalStateException("Queue is full!");
26 | }
27 |
28 | int avail = (this.front + this.storedSize) % array.length;
29 | array[avail] = element;
30 | this.storedSize++;
31 | }
32 |
33 | @Override
34 | public E dequeue() {
35 | if (isEmpty()) {
36 | return null;
37 | }
38 |
39 | E element = first();
40 | array[front] = null;
41 | this.front = (this.front + 1) % array.length;
42 | this.storedSize--;
43 | return element;
44 | }
45 |
46 | @Override
47 | public int size() {
48 | return this.storedSize;
49 | }
50 |
51 | @Override
52 | public boolean isEmpty() {
53 | return this.storedSize == 0;
54 | }
55 |
56 | @Override
57 | public E first() {
58 | if (isEmpty()) {
59 | return null;
60 | }
61 |
62 | return array[front];
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/ArrayStack.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class ArrayStack implements Stack {
8 |
9 | private static final int CAPACITY = 1000;
10 | private int top = -1;
11 | private E[] array;
12 |
13 | public ArrayStack() {
14 | this(CAPACITY);
15 | }
16 |
17 | public ArrayStack(final int capacity) {
18 | this.array = (E[]) new Object[capacity]; // safe cast; compiler may give warning
19 | }
20 |
21 | @Override
22 | public void push(E e) {
23 | if (array.length == size()) {
24 | throw new IllegalStateException("Stack is full");
25 | }
26 |
27 | top++;
28 | array[top] = e;
29 | }
30 |
31 | @Override
32 | public E pop() {
33 | if (this.isEmpty()) {
34 | return null;
35 | }
36 |
37 | E e = array[top];
38 | array[top] = null;
39 | top--;
40 | return e;
41 | }
42 |
43 | @Override
44 | public E top() {
45 | if (this.isEmpty()) {
46 | return null;
47 | }
48 |
49 | return array[top];
50 | }
51 |
52 | @Override
53 | public int size() {
54 | return this.top + 1;
55 | }
56 |
57 | @Override
58 | public boolean isEmpty() {
59 | return this.top == -1;
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/ArrayUtil.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | /**
4 | *
5 | * @author Rogerio J. Gentil
6 | */
7 | public class ArrayUtil {
8 |
9 | private ArrayUtil() {}
10 |
11 | public static void reverse(E[] array) {
12 | Stack stack = new ArrayStack<>(array.length);
13 |
14 | for (int i = 0; i < array.length; i++) {
15 | stack.push(array[i]);
16 | }
17 |
18 | for (int i = 0; i < array.length; i++) {
19 | array[i] = stack.pop();
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/CircularQueue.java:
--------------------------------------------------------------------------------
1 |
2 | package rogeriogentil.data.structures.chapter06;
3 |
4 | /**
5 | *
6 | * @author Rogerio J. Gentil
7 | */
8 | public interface CircularQueue extends Queue {
9 |
10 | /**
11 | * Rotates the front element of the queue to the back of the queue.
12 | * This does nothing if the queue is empty.
13 | */
14 | void rotate( );
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/Deque.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | /**
4 | *
5 | * @author Rogerio J. Gentil
6 | * @param
7 | */
8 | public interface Deque {
9 |
10 | /**
11 | * Inserts an element at the front of the deque.
12 | * @param element
13 | */
14 | void addFirst(E element);
15 |
16 | /**
17 | * Inserts an element at the back of the deque.
18 | * @param element
19 | */
20 | void addLast(E element);
21 |
22 | /**
23 | * Removes and returns the first element of the deque (null if empty).
24 | * @return
25 | */
26 | E removeFirst();
27 |
28 | /**
29 | * Removes and returns the last element of the deque (null if empty).
30 | * @return
31 | */
32 | E removeLast();
33 |
34 | /**
35 | * Returns, but does not remove, the first element of the deque (null if empty).
36 | * @return
37 | */
38 | E first();
39 |
40 | /**
41 | * Returns, but does not remove, the last element of the deque (null if empty).
42 | * @return
43 | */
44 | E last();
45 |
46 | /**
47 | * Returns the number of elements in the deque.
48 | * @return
49 | */
50 | int size();
51 |
52 | /**
53 | * Tests whether the deque is empty.
54 | * @return {@code true} or {@code false}
55 | */
56 | boolean isEmpty();
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/DoublyLinkedList.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | import rogeriogentil.data.structures.chapter03.*;
4 |
5 | /**
6 | * Copied class of the chapter 3.
7 | *
8 | * @author rogerio
9 | * @param
10 | */
11 | public class DoublyLinkedList implements Deque {
12 |
13 | private int size;
14 | private BiNode header;
15 | private BiNode trailer;
16 |
17 | public DoublyLinkedList() {
18 | header = new BiNode<>();
19 | trailer = new BiNode<>();
20 |
21 | header.setNext(trailer);
22 | trailer.setPrevious(header);
23 | }
24 |
25 | public BiNode getHeader() {
26 | return header;
27 | }
28 |
29 | public BiNode getTrailer() {
30 | return trailer;
31 | }
32 |
33 | @Override
34 | public boolean isEmpty() {
35 | return this.size == 0;
36 | }
37 |
38 | @Override
39 | public void addFirst(E element) {
40 | BiNode node = new BiNode<>(element);
41 | node.setPrevious(header);
42 | node.setNext(header.getNext());
43 |
44 | header.getNext().setPrevious(node);
45 | header.setNext(node);
46 |
47 | size++;
48 | }
49 |
50 | @Override
51 | public E first() {
52 | return this.header.getNext().getElement();
53 | }
54 |
55 | @Override
56 | public void addLast(E element) {
57 | BiNode node = new BiNode<>(element);
58 | node.setPrevious(trailer.getPrevious());
59 | node.setNext(trailer);
60 |
61 | trailer.getPrevious().setNext(node);
62 | trailer.setPrevious(node);
63 | size++;
64 | }
65 |
66 | @Override
67 | public E last() {
68 | return trailer.getPrevious().getElement();
69 | }
70 |
71 | @Override
72 | public E removeFirst() {
73 | if (isEmpty()) {
74 | return null;
75 | }
76 |
77 | E element = header.getNext().getElement();
78 | header.setNext(header.getNext().getNext());
79 | header.getNext().getNext().setPrevious(header);
80 | size--;
81 | return element;
82 | }
83 |
84 | @Override
85 | public E removeLast() {
86 | if (isEmpty()) {
87 | return null;
88 | }
89 |
90 | E element = trailer.getPrevious().getElement();
91 | trailer.setPrevious(trailer.getPrevious().getPrevious());
92 | trailer.getPrevious().getPrevious().setNext(trailer);
93 | size--;
94 | return element;
95 | }
96 |
97 | @Override
98 | public int size() {
99 | return size;
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/LinkedQueue.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | import rogeriogentil.data.structures.chapter03.SinglyLinkedList;
4 | import rogeriogentil.data.structures.chapter06.Queue;
5 |
6 | /**
7 | *
8 | * @author rogerio
9 | */
10 | public class LinkedQueue implements Queue {
11 |
12 | private SinglyLinkedList list = new SinglyLinkedList<>();
13 |
14 | @Override
15 | public void enqueue(E element) {
16 | list.addLast(element);
17 | }
18 |
19 | @Override
20 | public E dequeue() {
21 | return list.removeFist();
22 | }
23 |
24 | @Override
25 | public E first() {
26 | return list.first();
27 | }
28 |
29 | @Override
30 | public int size() {
31 | return list.getSize();
32 | }
33 |
34 | @Override
35 | public boolean isEmpty() {
36 | return list.isEmpty();
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/LinkedStack.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | import rogeriogentil.data.structures.chapter03.SinglyLinkedList;
4 |
5 | /**
6 | *
7 | * @author Rogerio J. Gentil
8 | */
9 | public class LinkedStack implements Stack {
10 |
11 | private SinglyLinkedList list = new SinglyLinkedList<>();
12 |
13 | @Override
14 | public void push(E e) {
15 | list.addFirst(e);
16 | }
17 |
18 | @Override
19 | public E pop() {
20 | return list.removeFist();
21 | }
22 |
23 | @Override
24 | public E top() {
25 | return list.first();
26 | }
27 |
28 | @Override
29 | public int size() {
30 | return list.getSize();
31 | }
32 |
33 | @Override
34 | public boolean isEmpty() {
35 | return list.isEmpty();
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/MatchUtil.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public class MatchUtil {
8 |
9 | public static boolean isMatched(String expression) {
10 | final String opening = "{[(";
11 | final String closing = "}])";
12 |
13 | Stack buffer = new LinkedStack<>();
14 |
15 | for (char c : expression.toCharArray()) {
16 | if (opening.indexOf(c) != -1) {
17 | buffer.push(c);
18 | } else if (closing.indexOf(c) != -1) {
19 | if (buffer.isEmpty()) {
20 | return false;
21 | }
22 |
23 | if (closing.indexOf(c) != opening.indexOf(buffer.pop())) {
24 | return false;
25 | }
26 | }
27 | }
28 |
29 | return buffer.isEmpty();
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/Queue.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public interface Queue {
8 |
9 | /**
10 | * Adds element e to the back of queue.
11 | * @param e
12 | */
13 | void enqueue(E element);
14 |
15 | /**
16 | * Removes and returns the first element from the queue (or null if the queue is empty).
17 | * @return E
18 | */
19 | E dequeue();
20 |
21 | /**
22 | * Returns the first element of the queue, without removing it (or null if the queue is empty).
23 | * @return The first element of the queue
24 | */
25 | E first();
26 |
27 | /**
28 | * Returns the number of elements in the queue.
29 | * @return
30 | */
31 | int size();
32 |
33 | /**
34 | * Returns a boolean indicating whether the queue is empty.
35 | * @return {@code true} or {@code false}
36 | */
37 | boolean isEmpty();
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/Stack.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06;
2 |
3 | /**
4 | *
5 | * @author rogerio
6 | */
7 | public interface Stack {
8 |
9 | /**
10 | * Adds element e to the top of the stack.
11 | *
12 | * @param e E
13 | */
14 | void push(E e);
15 |
16 | /**
17 | * Removes and returns the top element from the stack (or null if the stack is empty).
18 | *
19 | * @return E
20 | */
21 | E pop();
22 |
23 | /**
24 | * Returns the top element of the stack, without removing it (or null if the stack is empty).
25 | *
26 | * @return
27 | */
28 | E top();
29 |
30 | /**
31 | * Returns the number of elements in the stack.
32 | *
33 | * @return Size of stack
34 | */
35 | int size();
36 |
37 | /**
38 | * Returns a boolean indicating whether the stack is empty.
39 | *
40 | * @return {@code true} or {@code false}
41 | */
42 | boolean isEmpty();
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise01.txt:
--------------------------------------------------------------------------------
1 | R-6.1 Suppose an initially empty stack S has performed a total of 25 push operations, 12 top operations, and 10 pop
2 | operations, 3 of which returned null to indicate an empty stack. What is the current size of S?
3 |
4 | Answer (pt-BR):
5 | --------------
6 |
7 | Se foram realizadas 25 chamadas para o método push(e) - adiciona um elemento a pilha,
8 | 12 chamadas para top() - obtém o elemento apenas sem removê-lo,
9 | 10 chamadas para pop() - obtém o elemento no topo da pilha e remove-o -
10 | sendo que 3 chamadas para pop() retornaram 'null' - indicando que a pilha estava vazia,
11 | logo essas 3 chamadas que retornaram 'null' foram realizadas antes das chamadas para o método 'push(e)'.
12 | Portanto, conclui-se que o tamanho atual da pilha é 18 => 25 - (10 - 3).
13 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise02.txt:
--------------------------------------------------------------------------------
1 | R-6.2 Had the stack of the previous problem been an instance of the ArrayStack class, from Code Fragment 6.2, what
2 | would be the final value of the instance variable t?
3 |
4 | Answer (pt-BR)
5 | --------------
6 |
7 | Tendo a situação exercício anterior e usando levando em conta que foi usada uma instância da classe
8 | ArrayStack, o valor final da variável de instância 't' seria 14.
9 |
10 | inicial: t = -1
11 | final: size() = 15
12 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise03.txt:
--------------------------------------------------------------------------------
1 | R-6.3 What values are returned during the following series of stack operations, if executed upon an initially empty
2 | stack? push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6), pop(),
3 | pop(), push(4), pop(), pop().
4 |
5 | Answer (pt-BR)
6 | --------------
7 |
8 | Para uma pilha inicialmente vazia, são retornados os seguintes valores:
9 |
10 | Performed Returned Actually
11 | --------- -------- --------
12 | push(5) - (5)
13 | push(3) - (5, 3)
14 | pop() 3 (5)
15 | push(2) - (5, 2)
16 | push(8) - (5, 2, 8)
17 | pop() 8 (5, 2)
18 | pop() 2 (5)
19 | push(9) - (5, 9)
20 | push(1) - (5, 9, 1)
21 | pop() 1 (5, 9)
22 | push(7) - (5, 9, 7)
23 | push(6) - (5, 9, 7, 6)
24 | pop() 6 (5, 9, 7)
25 | pop() 7 (5, 9)
26 | push(4) - (5, 9, 4)
27 | pop() 4 (5, 9)
28 | pop() 9 (5)
29 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise04.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06.reinforcement;
2 |
3 | import rogeriogentil.data.structures.chapter06.Stack;
4 |
5 | /**
6 | * R-6.4 Implement a method with signature transfer(S, T ) that transfers all elements from stack S onto stack T , so
7 | * that the element that starts at the top of S is the first to be inserted onto T , and the element at the bottom of
8 | * S ends up at the top of T.
9 | *
10 | * @author Rogerio J. Gentil
11 | */
12 | public class Exercise04 {
13 |
14 | public static void transfer(Stack s, Stack t) {
15 | if (s.isEmpty()) {
16 | throw new IllegalStateException("Stack S is empty!");
17 | }
18 |
19 | while (s.top() != null) {
20 | t.push(s.pop());
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise05.java:
--------------------------------------------------------------------------------
1 |
2 | package rogeriogentil.data.structures.chapter06.reinforcement;
3 |
4 | import rogeriogentil.data.structures.chapter06.Stack;
5 |
6 | /**
7 | * R-6.5 Give a recursive method for removing all the elements from a stack.
8 | *
9 | * @author Rogerio J. Gentil
10 | * @param
11 | */
12 | public class Exercise05 {
13 |
14 | public void removeAll(Stack stack) {
15 | if (stack.pop() == null) {
16 | return;
17 | }
18 | stack.pop();
19 | removeAll(stack);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise07.txt:
--------------------------------------------------------------------------------
1 | R-6.7 Suppose an initially empty queue Q has performed a total of 32 enqueue operations, 10 first operations,
2 | and 15 dequeue operations, 5 of which returned null to indicate an empty queue. What is the current size of Q?
3 |
4 | Answer
5 | ------
6 | If 5 dequeue operations returned null, so only 10 dequeue operations remove some element of the queue. Thus,
7 | the current size of Q is 22.
8 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise08.txt:
--------------------------------------------------------------------------------
1 | R-6.8 Had the queue of the previous problem been an instance of the ArrayQueue class, from Code Fragment 6.10, with
2 | capacity 30 never exceeded, what would be the final value of the instance variable f?
3 |
4 | Answer
5 | ------
6 |
7 | The previous problem: R-6.7
8 | - 32 enqueue operations,
9 | - 10 first operations, and
10 | - 15 dequeue operations, 5 of which returned null to indicate an empty queue.
11 |
12 | Therefore,
13 | - the first operation don't change the variable f
14 | - only 10 (15 - 5) operations dequeue has removed some element of the queue
15 |
16 | The instance variable f that indicates the index of the front element was just changed when performed the dequeue
17 | operation. Thus, the final value of the variable f is 10.
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise09.txt:
--------------------------------------------------------------------------------
1 | R-6.9 What values are returned during the following sequence of queue operations, if executed on an initially empty
2 | queue? enqueue(5), enqueue(3), dequeue(), enqueue(2), enqueue(8), dequeue(), dequeue(), enqueue(9), enqueue(1),
3 | dequeue(), enqueue(7), enqueue(6), dequeue(), dequeue(), enqueue(4), dequeue(), dequeue().
4 |
5 | Answer
6 | ------
7 |
8 | Operation Returned value Contents queue
9 | --------- -------------- --------------
10 | enqueue(5) - (5)
11 | enqueue(3) - (5, 3)
12 | dequeue() 5 (3)
13 | enqueue(2) - (3, 2)
14 | enqueue(8) - (3, 2, 8)
15 | dequeue() 3 (2, 8)
16 | dequeue() 2 (8)
17 | enqueue(9) - (8, 9)
18 | enqueue(1) - (8, 9, 1)
19 | dequeue() 8 (9, 1)
20 | enqueue(7) - (9, 1, 7)
21 | enqueue(6) - (9, 1, 7, 6)
22 | dequeue() 9 (1, 7, 6)
23 | dequeue() 1 (7, 6)
24 | enqueue(4) - (7, 6, 4)
25 | dequeue() 7 (6, 4)
26 | dequeue() 6 (4)
27 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise10.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter06.reinforcement;
2 |
3 | import rogeriogentil.data.structures.chapter06.Deque;
4 | import rogeriogentil.data.structures.chapter06.DoublyLinkedList;
5 | import rogeriogentil.data.structures.chapter06.Stack;
6 |
7 | /**
8 | * R-6.10 Give a simple adapter that implements the stack ADT while using an instance of a deque for storage.
9 | *
10 | * @author Rogerio J. Gentil
11 | * @param
12 | */
13 | public class Exercise10 implements Stack {
14 |
15 | private Deque deque;
16 |
17 | public Exercise10() {
18 | this.deque = new DoublyLinkedList<>();
19 | }
20 |
21 | @Override
22 | public void push(E e) {
23 | this.deque.addLast(e);
24 | }
25 |
26 | @Override
27 | public E pop() {
28 | return this.deque.removeLast();
29 | }
30 |
31 | @Override
32 | public E top() {
33 | return this.deque.last();
34 | }
35 |
36 | @Override
37 | public int size() {
38 | return this.deque.size();
39 | }
40 |
41 | @Override
42 | public boolean isEmpty() {
43 | return this.deque.isEmpty();
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter06/reinforcement/Exercise12.txt:
--------------------------------------------------------------------------------
1 | R-6.12 What values are returned during the following sequence of deque ADT operations, on an initially empty deque?
2 | addFirst(3), addLast(8), addLast(9), addFirst(1), last( ), isEmpty( ), addFirst(2), removeLast( ), addLast(7),
3 | first( ), last( ), addLast(4), size( ), removeFirst( ), removeFirst( ).
4 |
5 | Answer
6 | ------
7 |
8 | Operation Returned value Content of the deque
9 | ----------- -------------- --------------------
10 | addFirst(3) - (3)
11 | addLast(8) - (3, 8)
12 | addLast(9) - (3, 8, 9)
13 | addFirst(1) - (1, 3, 8, 9)
14 | last() 9 (1, 3, 8, 9)
15 | isEmpty() false (1, 3, 8, 9)
16 | addFirst(2) - (2, 1, 3, 8, 9)
17 | removeLast() 9 (2, 1, 3, 8)
18 | addLast(7) - (2, 1, 3, 8, 7)
19 | first() 2 (2, 1, 3, 8, 7)
20 | last() 7 (2, 1, 3, 8, 7)
21 | addLast(4) - (2, 1, 3, 8, 7, 4)
22 | size() 6 (2, 1, 3, 8, 7, 4)
23 | removeFirst() 2 (1, 3, 8, 7, 4)
24 | removeFirst() 1 (3, 8, 7, 4)
25 |
26 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/ArrayList.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter07;
2 |
3 | /**
4 | *
5 | * @author Rogerio J. Gentil
6 | * @param
7 | */
8 | public class ArrayList implements List {
9 |
10 | private static final int CAPACITY = 16;
11 | private int size = 0;
12 | private E[] data;
13 |
14 | public ArrayList(final int capacity) {
15 | data = (E[]) new Object[capacity];
16 | }
17 |
18 | public ArrayList() {
19 | this(CAPACITY);
20 | }
21 |
22 | protected void checkIndex(int i) {
23 | if (i < 0 || i > data.length) {
24 | throw new IndexOutOfBoundsException("Invalid index.");
25 | }
26 | }
27 |
28 | @Override
29 | public E get(int i) throws IndexOutOfBoundsException {
30 | checkIndex(i);
31 | return data[i];
32 | }
33 |
34 | @Override
35 | public E set(int i, E e) throws IndexOutOfBoundsException {
36 | checkIndex(i);
37 | E removed = data[i];
38 | data[i] = e;
39 | return removed;
40 | }
41 |
42 | @Override
43 | public void add(int i, E e) throws IndexOutOfBoundsException, IllegalStateException {
44 | checkIndex(i);
45 |
46 | if (size == data.length) {
47 | // throw new IllegalStateException("ArrayList is full!"); // before create resize method
48 | resize(data.length * 2);
49 | }
50 |
51 | for (int k = size - 1; k >= i; k--) {
52 | data[k+1] = data[k];
53 | }
54 |
55 | data[i] = e;
56 | size++;
57 | }
58 |
59 | @Override
60 | public E remove(int i) throws IndexOutOfBoundsException {
61 | checkIndex(i);
62 | E removed = data[i];
63 |
64 | for (int k = i; k < size - 1; k++) {
65 | data[k] = data[k+1];
66 | }
67 |
68 | data[size - 1] = null; // help GC
69 | size--;
70 | return removed;
71 | }
72 |
73 | @Override
74 | public int size() {
75 | return this.size;
76 | }
77 |
78 | @Override
79 | public boolean isEmpty() {
80 | return this.size == 0;
81 | }
82 |
83 | protected void resize(final int capacity) {
84 | E[] temp = (E[]) new Object[capacity];
85 | for (int i = 0; i < size; i++) {
86 | temp[i] = data[i];
87 | }
88 | data = temp; // sustitui a referência do array
89 | }
90 |
91 | // ----- Method added on resolution of the exercise R-7.5
92 | public void trimToSize() {
93 | E[] temp = (E[]) new Object[this.size()];
94 |
95 | for (int i = 0; i < this.size(); i++) {
96 | temp[i] = this.data[i];
97 | }
98 |
99 | // Alternative to 'for'
100 | // System.arraycopy(this.data, 0, temp, 0, this.size());
101 |
102 | this.data = temp;
103 | temp = null; // GC helper
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/List.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter07;
2 |
3 | /**
4 | *
5 | * @author Rogerio J. Gentil
6 | */
7 | public interface List {
8 |
9 |
10 | /**
11 | * Returns (but does not remove) the element at index i
12 | * @param i
13 | * @return
14 | * @throws IndexOutOfBoundsException
15 | */
16 | E get(int i) throws IndexOutOfBoundsException;
17 |
18 | /**
19 | * Replaces the element at index i with e, and returns the replaced element.
20 | * @param i
21 | * @param e
22 | * @return
23 | * @throws IndexOutOfBoundsException
24 | */
25 | E set(int i, E e) throws IndexOutOfBoundsException;
26 |
27 | /**
28 | * Inserts element e to be at index i, shifting all subsequent elements later.
29 | * @param i
30 | * @param e
31 | * @throws IndexOutOfBoundsException
32 | */
33 | void add(int i, E e) throws IndexOutOfBoundsException;
34 |
35 | /**
36 | * Removes/returns the element at index i, shifting subsequent elements earlier.
37 | * @param i
38 | * @return
39 | * @throws IndexOutOfBoundsException
40 | */
41 | E remove(int i) throws IndexOutOfBoundsException;
42 |
43 | /**
44 | * Returns the number of elements in this list.
45 | * @return
46 | */
47 | int size();
48 |
49 | /**
50 | * Returns whether the list is empty.
51 | * @return
52 | */
53 | boolean isEmpty();
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/Position.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter07;
2 |
3 | /**
4 | *
5 | * @author Rogerio J. Gentil
6 | */
7 | public interface Position {
8 |
9 | /**
10 | * Returns the element stored at this position.
11 | *
12 | * @return An element
13 | * @throws IllegalStateException if position no longer valid
14 | */
15 | E getElement() throws IllegalStateException;
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/PositionalList.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter07;
2 |
3 | /**
4 | *
5 | * @author Rogerio J. Gentil
6 | */
7 | public interface PositionalList {
8 |
9 | Position first();
10 |
11 | Position last();
12 |
13 | /**
14 | * Returns the Position immediately before Position p (or null, if p is first).
15 | * @param p
16 | * @return
17 | * @throws IllegalStateException
18 | */
19 | Position before(Position p) throws IllegalStateException;
20 |
21 | /**
22 | * Returns the Position immediately after Position p (or null, if p is last).
23 | * @param p
24 | * @return
25 | * @throws IllegalStateException
26 | */
27 | Position after(Position p) throws IllegalStateException;
28 |
29 | /**
30 | * Inserts element e at the front of the list and returns its new Position.
31 | * @param element
32 | * @return
33 | */
34 | Position addFirst(E element);
35 |
36 | /**
37 | * Inserts element e at the back of the list and returns its new Position.
38 | * @param element
39 | * @return
40 | */
41 | Position addLast(E element);
42 |
43 | /**
44 | * Inserts element e immediately before Position p and returns its new Position.
45 | * @param p
46 | * @param element
47 | * @return
48 | * @throws IllegalStateException
49 | */
50 | Position addBefore(Position p, E element) throws IllegalStateException;
51 |
52 | /**
53 | * Inserts element e immediately after Position p and returns its new Position.
54 | * @param p
55 | * @param element
56 | * @return
57 | * @throws IllegalStateException
58 | */
59 | Position addAfter(Position p, E element) throws IllegalStateException;
60 |
61 | /**
62 | * Replaces the element stored at Position p and returns the replaced element.
63 | * @param p
64 | * @param element
65 | * @return
66 | * @throws IllegalStateException
67 | */
68 | E set(Position p, E element) throws IllegalStateException;
69 |
70 | /**
71 | * Removes the element stored at Position p and returns it (invalidating p).
72 | * @param p
73 | * @return
74 | * @throws IllegalArgumentException
75 | */
76 | E remove(Position p) throws IllegalArgumentException;
77 |
78 | int size();
79 |
80 | boolean isEmpty();
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/reinforcement/Exercise01.txt:
--------------------------------------------------------------------------------
1 | Q: Draw a representation, akin to Example 7.1, of an initially empty list L after per-
2 | forming the following sequence of operations: add(0, 4), add(0, 3), add(0, 2),
3 | add(2, 1), add(1, 5), add(1, 6), add(3, 7), add(0, 8).
4 |
5 | add(0, 4) - (4)
6 | add(0, 3) - (3, 4)
7 | add(0, 2) - (2, 3, 4)
8 | add(2, 1) - (2, 3, 1, 4)
9 | add(1, 5) - (2, 5, 3, 1, 4)
10 | add(1, 6) - (2, 6, 5, 3, 1, 4)
11 | add(3, 7) - (2, 6, 5, 7, 3, 1, 4)
12 | add(0, 8) - (8, 2, 6, 5, 7, 3, 1, 4)
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/reinforcement/Exercise02.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter07.reinforcement;
2 |
3 | import rogeriogentil.data.structures.chapter06.Stack;
4 | import rogeriogentil.data.structures.chapter07.ArrayList;
5 |
6 | /**
7 | *
8 | * @author Rogerio J. Gentil
9 | */
10 | public class Exercise02 {
11 | }
12 |
13 | /**
14 | * R-7.2 Give an implementation of the stack ADT using an array list for storage.
15 | */
16 | class StackArrayList implements Stack {
17 |
18 | private static final int CAPACITY = 16;
19 | private ArrayList data;
20 |
21 | public StackArrayList(final int capacity) {
22 | data = new ArrayList<>(capacity);
23 | }
24 |
25 | public StackArrayList() {
26 | this(CAPACITY);
27 | }
28 |
29 | @Override
30 | public E top() {
31 | return data.get(this.size() - 1);
32 | }
33 |
34 | @Override
35 | public E pop() {
36 | return data.remove(this.size() - 1);
37 | }
38 |
39 | @Override
40 | public void push(E element) {
41 | data.add(size(), element);
42 | }
43 |
44 | @Override
45 | public boolean isEmpty() {
46 | return this.data.size() == 0;
47 | }
48 |
49 | @Override
50 | public int size() {
51 | return this.data.size();
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/reinforcement/Exercise03.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter07.reinforcement;
2 |
3 | import rogeriogentil.data.structures.chapter06.Deque;
4 | import rogeriogentil.data.structures.chapter07.ArrayList;
5 |
6 | /**
7 | *
8 | * @author Rogerio J. Gentil
9 | */
10 | public class Exercise03 {
11 | }
12 |
13 | /**
14 | * R-7.3 Give an implementation of the deque ADT using an array list for storage.
15 | *
16 | * @author rogerio
17 | */
18 | class DequeArrayList implements Deque {
19 |
20 | private static final int CAPACITY = 32;
21 | private ArrayList data;
22 |
23 | public DequeArrayList(final int capacity) {
24 | data = new ArrayList<>(capacity);
25 | }
26 |
27 | public DequeArrayList() {
28 | this(CAPACITY);
29 | }
30 |
31 | @Override
32 | public void addFirst(E element) {
33 | this.data.add(0, element);
34 | }
35 |
36 | @Override
37 | public void addLast(E element) {
38 | this.data.add(this.data.size(), element);
39 | }
40 |
41 | @Override
42 | public E removeFirst() {
43 | return this.data.remove(0);
44 | }
45 |
46 | @Override
47 | public E removeLast() {
48 | return this.data.remove(this.data.size() - 1);
49 | }
50 |
51 | @Override
52 | public E first() {
53 | return this.data.get(0);
54 | }
55 |
56 | @Override
57 | public E last() {
58 | return this.data.get(this.data.size() - 1);
59 | }
60 |
61 | @Override
62 | public int size() {
63 | return this.data.size();
64 | }
65 |
66 | @Override
67 | public boolean isEmpty() {
68 | return this.data.size() == 0;
69 | }
70 |
71 | }
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/reinforcement/Exercise05.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter07.reinforcement;
2 |
3 | import rogeriogentil.data.structures.chapter07.ArrayList;
4 |
5 | /**
6 | * R-7.5 The java.util.ArrayList includes a method, trimToSize(), that replaces
7 | * the underlying array with one whose capacity precisely equals the number of
8 | * elements currently in the list. Implement such a method for our dynamic
9 | * version of the ArrayList class from Section 7.2.
10 | *
11 | * Details: https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html#trimToSize--
12 | *
13 | * @author Rogerio J. Gentil
14 | * @param
15 | */
16 | public class Exercise05 {
17 |
18 | /**
19 | * See the method trimToSize() in the class ArrayList
20 | */
21 | public void trimToSize() {
22 | ArrayList list = new ArrayList<>();
23 | list.trimToSize();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter07/reinforcement/Exercise10.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter07.reinforcement;
2 |
3 | import rogeriogentil.data.structures.chapter06.Stack;
4 | import rogeriogentil.data.structures.chapter07.ArrayList;
5 |
6 | /**
7 | * R-7.10 Reimplement the ArrayStack class, from Section 6.1.2, using dynamic
8 | * arrays to support unlimited capacity.
9 | *
10 | * @author Rogerio J. Gentil
11 | */
12 | public class Exercise10 {}
13 |
14 | class ArrayStack implements Stack {
15 |
16 | private ArrayList data;
17 |
18 | public ArrayStack() {
19 | this.data = new ArrayList();
20 | }
21 |
22 | @Override
23 | public void push(E e) {
24 | this.data.add(this.size(), e);
25 | }
26 |
27 | @Override
28 | public E pop() {
29 | return this.data.remove(size() - 1);
30 | }
31 |
32 | @Override
33 | public E top() {
34 | int i = this.size() - 1;
35 | return this.data.get(i);
36 | }
37 |
38 | @Override
39 | public int size() {
40 | return this.data.size();
41 | }
42 |
43 | @Override
44 | public boolean isEmpty() {
45 | return this.data.isEmpty();
46 | }
47 | }
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/AbstractBinaryTree.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter08;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import rogeriogentil.data.structures.chapter07.Position;
6 |
7 | /**
8 | *
9 | * @author Rogerio J. Gentil
10 | * @param
11 | */
12 | public abstract class AbstractBinaryTree extends AbstractTree implements BinaryTree {
13 |
14 | @Override
15 | public Position sibling(Position position) throws IllegalArgumentException {
16 | Position parent = parent(position);
17 |
18 | if (parent == null) {
19 | return null; // p must be the root
20 | }
21 |
22 | if (position == left(parent)) {
23 | return right(parent);
24 | }
25 |
26 | return left(parent);
27 | }
28 |
29 | @Override
30 | public int numChildren(Position position) {
31 | int count = 0;
32 |
33 | if (left(position) != null) {
34 | count++;
35 | }
36 |
37 | if (right(position) != null) {
38 | count++;
39 | }
40 |
41 | return count;
42 | }
43 |
44 | @Override
45 | public Iterable> children(Position position) {
46 | List> snapshot = new ArrayList<>(2); // max capacity of 2
47 |
48 | if (left(position) != null) {
49 | snapshot.add(left(position));
50 | }
51 |
52 | if (right(position) != null) {
53 | snapshot.add(right(position));
54 | }
55 |
56 | return snapshot;
57 | }
58 |
59 | /**
60 | * Adds positions of the subtree rooted at a position to the given snapshot.
61 | *
62 | * @param position
63 | * @param snapshot
64 | */
65 | private void inOrderSubtree(Position position, List> snapshot) {
66 | if (left(position) != null) {
67 | inOrderSubtree(left(position), snapshot);
68 | }
69 |
70 | snapshot.add(position);
71 |
72 | if (right(position) != null) {
73 | inOrderSubtree(right(position), snapshot);
74 | }
75 | }
76 |
77 | /**
78 | * Returns an iterable collection of positions of the tree, reported in inorder.
79 | *
80 | * @return
81 | */
82 | public Iterable> inOrder() {
83 | List> snapshot = new ArrayList<>();
84 |
85 | if (!isEmpty()) {
86 | inOrderSubtree(root(), snapshot); // fill the snapshot recursively
87 | }
88 |
89 | return snapshot;
90 | }
91 |
92 | @Override
93 | public Iterable> positions() {
94 | return inOrder();
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/AbstractTree.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter08;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import rogeriogentil.data.structures.chapter06.LinkedQueue;
6 | import rogeriogentil.data.structures.chapter06.Queue;
7 | import rogeriogentil.data.structures.chapter07.Position;
8 |
9 | /**
10 | *
11 | * @author Rogerio J. Gentil
12 | * @param
13 | */
14 | public abstract class AbstractTree implements Tree {
15 |
16 | @Override
17 | public boolean isInternal(Position position) throws IllegalStateException {
18 | return numChildren(position) > 0;
19 | }
20 |
21 | @Override
22 | public boolean isExternal(Position position) throws IllegalStateException {
23 | return numChildren(position) == 0;
24 | }
25 |
26 | @Override
27 | public boolean isRoot(Position position) throws IllegalStateException {
28 | return position == root();
29 | }
30 |
31 | @Override
32 | public boolean isEmpty() {
33 | return size() == 0;
34 | }
35 |
36 | public int depth(Position position) {
37 | if (isRoot(position)) {
38 | return 0;
39 | }
40 |
41 | return 1 + depth(parent(position));
42 | }
43 |
44 | /**
45 | * Returns the height of the subtree rooted at Position p.
46 | *
47 | * @param position
48 | * @return
49 | */
50 | public int height(Position position) {
51 | int height = 0;
52 |
53 | for (Position child : children(position)) {
54 | height = Math.max(height, 1 + height(child));
55 | }
56 |
57 | return height;
58 | }
59 |
60 | /**
61 | * Returns the height of the tree.
62 | *
63 | * @return
64 | */
65 | private int heightBad() { // works, but quadratic worst-case time
66 | int height = 0;
67 | for (Position position : positions()) {
68 | if (isExternal(position)) {
69 | height = Math.max(height, depth(position));
70 | }
71 | }
72 |
73 | return height;
74 | }
75 |
76 | /**
77 | * Adds positions of the subtree rooted at position to the given snapshot.
78 | *
79 | * @param position
80 | * @param snapshot
81 | */
82 | private void preOrderSubtree(Position position, List> snapshot) {
83 | snapshot.add(position); // for preorder, we add position before exploring subtrees
84 |
85 | for (Position child : children(position)) {
86 | preOrderSubtree(child, snapshot);
87 | }
88 | }
89 |
90 | /**
91 | * Returns an iterable collection of positions of the tree, reported in preorder.
92 | *
93 | * @return
94 | */
95 | public Iterable> preOrder() {
96 | List> snapshot = new ArrayList<>();
97 | if (!isEmpty()) {
98 | preOrderSubtree(root(), snapshot);
99 | }
100 |
101 | return snapshot;
102 | }
103 |
104 | /**
105 | * Adds positions of the subtree rooted at Position p to the given snapshot.
106 | * @param position
107 | * @param snapshot
108 | */
109 | private void postOrderSubtree(Position position, List> snapshot) {
110 | for (Position child : children(position)) {
111 | postOrderSubtree(child, snapshot);
112 | }
113 |
114 | snapshot.add(position); // for preorder, we add position before exploring subtrees
115 | }
116 |
117 | public Iterable> postOrder() {
118 | List> snapshot = new ArrayList<>();
119 | if (!isEmpty()) {
120 | postOrderSubtree(root(), snapshot);
121 | }
122 |
123 | return snapshot;
124 | }
125 |
126 | /**
127 | * Returns an iterable collection of positions of the tree in breadth-first order.
128 | *
129 | * @return
130 | */
131 | public Iterable> breathFirst() {
132 | List> snapshot = new ArrayList<>();
133 |
134 | if (!isEmpty()) {
135 | Queue> fringe = new LinkedQueue<>();
136 | fringe.enqueue(root());
137 |
138 | while (!fringe.isEmpty()) {
139 | Position position = fringe.dequeue();
140 | snapshot.add(position);
141 |
142 | for (Position child : children(position)) {
143 | fringe.enqueue(child);
144 | }
145 | }
146 | }
147 |
148 | return snapshot;
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/BinaryTree.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter08;
2 |
3 | import rogeriogentil.data.structures.chapter07.Position;
4 |
5 | /**
6 | *
7 | * @author Rogerio J. Gentil
8 | * @param
9 | */
10 | public interface BinaryTree extends Tree {
11 |
12 | /**
13 | * Returns the Position of p's left child (or null if no child exists).
14 | * @param position
15 | * @return
16 | * @throws IllegalArgumentException
17 | */
18 | Position left(Position position) throws IllegalArgumentException;
19 |
20 | /**
21 | * Returns the Position of p's right child (or null if no child exists).
22 | * @param position
23 | * @return
24 | * @throws IllegalArgumentException
25 | */
26 | Position right(Position position) throws IllegalArgumentException;
27 |
28 | /**
29 | * Returns the Position of p's sibling (or null if no sibling exists).
30 | * @param position
31 | * @return
32 | * @throws IllegalArgumentException
33 | */
34 | Position sibling(Position position) throws IllegalArgumentException;
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/Tree.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter08;
2 |
3 | import java.util.Iterator;
4 | import rogeriogentil.data.structures.chapter07.Position;
5 |
6 | /**
7 | *
8 | * @author Rogerio J. Gentil
9 | * @param
10 | */
11 | public interface Tree extends Iterable {
12 |
13 | /**
14 | * Returns the position of the root of the tree (or null if empty).
15 | * @return
16 | */
17 | Position root();
18 |
19 | /**
20 | * Returns the position of the parent of position p (or null if p is the root).
21 | * @param position
22 | * @return
23 | */
24 | Position parent(Position position) throws IllegalStateException;
25 |
26 | /**
27 | * Returns an iterable collection containing the children of position p (if any).
28 | * @param position
29 | * @return
30 | */
31 | Iterable> children(Position position) throws IllegalStateException;
32 |
33 | /**
34 | * Returns the number of children of position p.
35 | * @param position
36 | * @return
37 | */
38 | int numChildren(Position position) throws IllegalStateException;
39 |
40 | /**
41 | * Returns true if position p has at least one child.
42 | * @param position
43 | * @return
44 | */
45 | boolean isInternal(Position position) throws IllegalStateException;
46 |
47 | /**
48 | * Returns true if position p does not have any children.
49 | * @param position
50 | * @return
51 | */
52 | boolean isExternal(Position position) throws IllegalStateException;
53 |
54 | /**
55 | * Returns true if position p is the root of the tree.
56 | * @param position
57 | * @return
58 | */
59 | boolean isRoot(Position position) throws IllegalStateException;
60 |
61 | int size();
62 |
63 | boolean isEmpty();
64 |
65 | /**
66 | * Returns an iterator for all elements in the tree (so that the tree itself is Iterable).
67 | * @return
68 | */
69 | @Override
70 | Iterator iterator();
71 |
72 | /**
73 | * Returns an iterable collection of all positions of the tree.
74 | * @return
75 | */
76 | Iterable> positions();
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/TreeUtil.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter08;
2 |
3 | import java.util.List;
4 | import rogeriogentil.data.structures.chapter07.Position;
5 |
6 | /**
7 | *
8 | * @author Rogerio J. Gentil
9 | */
10 | public class TreeUtil {
11 |
12 | /**
13 | * Prints preorder representation of subtree of a tree rooted at a position having a depth.
14 | *
15 | * @param
16 | * @param tree
17 | * @param position
18 | * @param depth
19 | */
20 | public static void printPreOrderIndent(Tree tree, Position position, int depth) {
21 | System.out.println(spaces(2 * depth) + position.getElement());
22 |
23 | for (Position child : tree.children(position)) {
24 | printPreOrderIndent(tree, child, depth + 1); // child depth is d+1
25 | }
26 | }
27 |
28 | /**
29 | * Prints labeled representation of subtree of the tree rooted at a position having a depth.
30 | *
31 | * @param
32 | * @param tree
33 | * @param position
34 | * @param path
35 | */
36 | public static void printPreOrderLabeled(Tree tree, Position position, List path) {
37 | int depth = path.size(); // depth equals the length of the path
38 | System.out.print(spaces(2 * depth));
39 |
40 | for (int j = 0; j < depth; j++) {
41 | System.out.print(path.get(j) + (j == depth - 1 ? " " : "."));
42 | }
43 |
44 | System.out.println(position.getElement());
45 |
46 | path.add(1); // add path entry for first child
47 |
48 | for (Position child : tree.children(position)) {
49 | printPreOrderLabeled(tree, child, path);
50 | path.set(depth, 1 + path.get(depth)); // increment last entry of path
51 | }
52 |
53 | path.remove(depth);
54 | }
55 |
56 | /**
57 | * Prints parenthesized representation of subtree of the tree rooted at a position
58 | *
59 | * @param
60 | * @param tree
61 | * @param position
62 | */
63 | public static void paranthesize(Tree tree, Position position) {
64 | System.out.println(position.getElement());
65 |
66 | if (tree.isInternal(position)) {
67 | boolean firstTime = true;
68 |
69 | for (Position child : tree.children(position)) {
70 | System.out.println(firstTime ? "(" : ", ");
71 | firstTime = false;
72 | paranthesize(tree, child);
73 | }
74 |
75 | System.out.println(")");
76 | }
77 | }
78 |
79 | private static String spaces(int n) {
80 | StringBuilder sb = new StringBuilder();
81 | for (int i = 0; i < n; i++) {
82 | sb.append(" ");
83 | }
84 | return sb.toString();
85 | }
86 |
87 | /**
88 | * Recursive method for computing coordinates at which to draw positions of a binary tree. We assume that the element
89 | * type for the tree supports setX and setY methods. The initial call should be layout(T, T.root( ), 0, 0).
90 | *
91 | * @param
92 | * @param binaryTree
93 | * @param position
94 | * @param depth
95 | * @param x
96 | * @return
97 | */
98 | // public static int layout(BinaryTree binaryTree, Position position, int depth, int x) {
99 | // if (binaryTree.left(position) != null) {
100 | // x = layout(binaryTree, binaryTree.left(position), depth + 1, x); // resulting x will be increased
101 | // }
102 | //
103 | // position.getElement().setX(x++);
104 | // position.getElement().setY(depth);
105 | //
106 | // if (binaryTree.right(position) != null) {
107 | // x = layout(binaryTree, binaryTree.right(position), depth + 1, x); // resulting x will be increased
108 | // }
109 | //
110 | // return x;
111 | // }
112 | }
113 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise01.txt:
--------------------------------------------------------------------------------
1 | R-8.1 The following questions refer to the tree of Figure 8.3.
2 | a. Which node is the root?
3 | /user/rt/courses/
4 |
5 | b. What are the internal nodes?
6 | /user/rt/courses/
7 | cs016/
8 | homeworks/
9 | programs/
10 | cs252/
11 | projects/
12 | papers/
13 | demos/
14 |
15 | c. How many descendants does node cs016/ have?
16 | Does have 9 descendants
17 |
18 | d. How many ancestors does node cs016/ have?
19 | Just one ancestor: "/user/rt/courses/"
20 |
21 | e. What are the siblings of node homeworks/?
22 | "grades" and "programs/"
23 |
24 | f. Which nodes are in the subtree rooted at node projects/?
25 | papers/
26 | buylow
27 | sellhigh
28 | market
29 | demos/
30 |
31 | g. What is the depth of node papers/?
32 | The depth is 3
33 |
34 | h. What is the height of the tree?
35 | The height is 4
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise05.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter08.reinforcement;
2 |
3 | import rogeriogentil.data.structures.chapter07.Position;
4 | import rogeriogentil.data.structures.chapter08.BinaryTree;
5 |
6 | /**
7 | * R-8.5 Describe an algorithm, relying only on the BinaryTree operations, that counts the number of leaves in a binary
8 | * tree that are the left child of their respective parent.
9 | *
10 | * @author Rogerio J. Gentil
11 | */
12 | public class Exercise05 {
13 |
14 | public static int countLeftLeaves(BinaryTree binaryTree, Position position) {
15 | int count = 0;
16 |
17 | if (binaryTree.isEmpty() || binaryTree.size() == 1) {
18 | return count;
19 | }
20 |
21 | Position parent = binaryTree.parent(position);
22 |
23 | if (binaryTree.isExternal(position) && binaryTree.left(parent) == position) {
24 | return count + 1;
25 | } else {
26 | if (binaryTree.left(position) != null) {
27 | count += countLeftLeaves(binaryTree, binaryTree.left(position));
28 | }
29 |
30 | if (binaryTree.right(position) != null) {
31 | count += countLeftLeaves(binaryTree, binaryTree.right(position));
32 | }
33 |
34 | }
35 |
36 | return count;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise07.txt:
--------------------------------------------------------------------------------
1 | R-8.7 What are the minimum and maximum number of internal and external nodes in
2 | an improper binary tree with n nodes?
3 |
4 | Answer:
5 | - Minimum internal nodes: 1 node
6 | - Minimum external nodes: 1 node
7 | - Maximum internal nodes:
8 | - Maximum external nodes:
9 |
10 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise12.txt:
--------------------------------------------------------------------------------
1 | R-8.12 Draw the binary tree representation of the following arithmetic expression:
2 | "(((5 + 2) ∗ (2 − 1))/((2 + 9) + ((7 − 2) − 1)) ∗ 8)"
3 |
4 | Answer:
5 | /
6 |
7 | * +
8 |
9 | + - + *
10 |
11 | 5 2 2 1 2 9 8 -
12 |
13 | 1 -
14 |
15 | 7 2
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise18.txt:
--------------------------------------------------------------------------------
1 | R-8.18 In what order are positions visited during a preorder traversal of the
2 | tree of Figure 8.6?
3 |
4 | Answer
5 | ------
6 |
7 | -, /, *, +, 3, 1, 3, +, -, 9, 5, 2, +, *, 3, -, 7, 4, 6
8 |
9 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise19.txt:
--------------------------------------------------------------------------------
1 | R-8.19 In what order are positions visited during a postorder traversal of the
2 | tree of Figure 8.6?
3 |
4 | Answer
5 | ------
6 |
7 | 3, 1, +, 3, *, 9, 5, -, 2, +, /, 3, 7, 4, -, *, 6, +, -
8 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise20.txt:
--------------------------------------------------------------------------------
1 | R-8.20 Let T be an ordered tree with more than one node. Is it possible that the
2 | preorder traversal of T visits the nodes in the same order as the postorder
3 | traversal of T? If so, give an example; otherwise, explain why this cannot occur.
4 | Likewise, is it possible that the preorder traversal of T visits the nodes in the
5 | reverse order of the postorder traversal of T? If so, give an example; otherwise,
6 | explain why this cannot occur.
7 |
8 | Answers
9 | -------
10 | "Is it possible that the preorder traversal of T visits the nodes in the same
11 | order as the postorder traversal of T?"
12 | A: No. Because, given a tree with two nodes, for instance, in the preorder the
13 | first node visited is the root whereas in the postorder the first node visited
14 | is a child.
15 |
16 | "is it possible that the preorder traversal of T visits the nodes in the reverse
17 | order of the postorder traversal of T?"
18 | A: Yes, but only when a tree has two nodes.
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise22.txt:
--------------------------------------------------------------------------------
1 | R-8.22 Draw a binary tree T that simultaneously satisfies the following:
2 | • Each internal node of T stores a single character.
3 | • A preorder traversal of T yields EXAMFUN.
4 | • An inorder traversal of T yields MAFXUEN.
5 |
6 | Answer
7 | ------
8 | E
9 |
10 | X N
11 |
12 | A U
13 |
14 | M F
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter08/reinforcement/Exercise24.txt:
--------------------------------------------------------------------------------
1 | R-8.24 Give the output of the method parenthesize(T, T.root( )), as described in
2 | Code Fragment 8.26, when T is the tree of Figure 8.6.
3 |
4 | Answer
5 | ------
6 |
7 | -(/(*(+(3,1),3),+(-(9,5),2)),+(*(3,-(7,4)),6))
8 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter09/AbstractPriorityQueue.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter09;
2 |
3 | import java.util.Comparator;
4 |
5 | /**
6 | *
7 | * @author Rogerio J. Gentil
8 | * @param
9 | * @param
10 | */
11 | public abstract class AbstractPriorityQueue implements PriorityQueue {
12 |
13 | private Comparator comparator;
14 |
15 | protected AbstractPriorityQueue(Comparator c) {
16 | this.comparator = c;
17 | }
18 |
19 | protected AbstractPriorityQueue() {
20 | this(new DefaultComparator());
21 | }
22 |
23 | /**
24 | * Method for comparing two entries according to key
25 | *
26 | * @param a
27 | * @param b
28 | * @return
29 | */
30 | protected int compare(Entry a, Entry b) {
31 | return comparator.compare(a.getKey(), b.getKey());
32 | }
33 |
34 | /**
35 | * Determines whether a key is valid.
36 | *
37 | * @param key
38 | * @return
39 | * @throws IllegalArgumentException
40 | */
41 | protected boolean checkKey(K key) throws IllegalArgumentException {
42 | try {
43 | return comparator.compare(key, key) == 0; // see if key can be compared to itself
44 | } catch (ClassCastException e) {
45 | throw new IllegalArgumentException("Incompatible key");
46 | }
47 | }
48 |
49 | @Override
50 | public boolean isEmpty() {
51 | return size() == 0;
52 | }
53 |
54 | //---------------- nested PQEntry class ---------------
55 | protected static class PQEntry implements Entry {
56 |
57 | private K key;
58 | private V value;
59 |
60 | public PQEntry(K key, V value) {
61 | this.key = key;
62 | this.value = value;
63 | }
64 |
65 | @Override
66 | public K getKey() {
67 | return this.key;
68 | }
69 |
70 | @Override
71 | public V getvalue() {
72 | return this.value;
73 | }
74 |
75 | // utilities not exposed as part of the Entry interface
76 | protected void setKey(K key) {
77 | this.key = key;
78 | }
79 |
80 | protected void setValue(V value) {
81 | this.value = value;
82 | }
83 | }
84 | //------------ end of nested PQEntry class ------------
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter09/AdaptablePriorityQueue.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter09;
2 |
3 | /**
4 | *
5 | * @author Rogerio J. Gentil
6 | */
7 | interface AdaptablePriorityQueue {
8 |
9 | void remove(Entry entry);
10 |
11 | void replaceKey(Entry entry, K key);
12 |
13 | void replaceValue(Entry entry, V value);
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter09/DefaultComparator.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter09;
2 |
3 | import java.util.Comparator;
4 |
5 | /**
6 | *
7 | * @author Rogerio J. Gentil
8 | */
9 | public class DefaultComparator implements Comparator {
10 |
11 | @Override
12 | public int compare(E a, E b) throws ClassCastException {
13 | return ((Comparable) a).compareTo(b);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter09/Entry.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter09;
2 |
3 | /**
4 | * Interface for a key-value pair
5 | *
6 | * @author Rogerio J. Gentil
7 | * @param key
8 | * @param value
9 | */
10 | public interface Entry {
11 |
12 | /**
13 | * Returns the key stored in this entry
14 | *
15 | * @return
16 | */
17 | K getKey();
18 |
19 | /**
20 | * Returns the value stored in this entry
21 | *
22 | * @return
23 | */
24 | V getvalue();
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter09/HeapPriorityQueue.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter09;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Comparator;
5 |
6 | /**
7 | *
8 | * @author Rogerio J. Gentil
9 | * @param
10 | * @param
11 | */
12 | public class HeapPriorityQueue extends AbstractPriorityQueue {
13 |
14 | protected ArrayList> heap = new ArrayList<>();
15 |
16 | public HeapPriorityQueue() {
17 | }
18 |
19 | public HeapPriorityQueue(Comparator c) {
20 | super(c);
21 | }
22 |
23 | public HeapPriorityQueue(K[] keys, V[] values) {
24 | super();
25 | for (int j = 0; j < Math.min(keys.length, values.length); j++) {
26 | heap.add(new PQEntry<>(keys[j], values[j]));
27 | }
28 | heapify();
29 | }
30 |
31 | // protected utilities
32 | protected int parent(int j) {
33 | return (j - 1) / 2;
34 | }
35 |
36 | protected int left(int j) {
37 | return 2 * j + 1;
38 | }
39 |
40 | protected int right(int j) {
41 | return 2 * j + 2;
42 | }
43 |
44 | protected boolean hasLeft(int j) {
45 | return this.left(j) < heap.size();
46 | }
47 |
48 | protected boolean hasRight(int j) {
49 | return this.right(j) < heap.size();
50 | }
51 |
52 | /**
53 | * Exchanges the entries at indices i and j of the array list.
54 | *
55 | * @param i
56 | * @param j
57 | */
58 | protected void swap(int i, int j) {
59 | Entry temp = heap.get(i);
60 | heap.set(i, heap.get(j));
61 | heap.set(j, temp);
62 | }
63 |
64 | /**
65 | * Moves the entry at index j higher, if necessary, to restore the heap
66 | * property.
67 | *
68 | * @param j
69 | */
70 | protected void upHeap(int j) {
71 | while (j > 0) { // continue until reaching root (or break statement)
72 | int p = parent(j);
73 |
74 | if (compare(heap.get(j), heap.get(p)) >= 0) {
75 | break;
76 | }
77 |
78 | swap(j, p);
79 | j = p; // continue from the parent's location
80 | }
81 | }
82 |
83 | /**
84 | * Moves the entry at index j lower, if necessary, to restore the heap
85 | * property.
86 | *
87 | * @param j
88 | */
89 | protected void downHeap(int j) {
90 | while (hasLeft(j)) { // continue to bottom (or break statement)
91 | int leftIndex = left(j);
92 | int smallChildIndex = leftIndex; // although right may be smaller
93 |
94 | if (hasRight(j)) {
95 | int rightIndex = right(j);
96 | if (compare(heap.get(leftIndex), heap.get(rightIndex)) > 0) {
97 | smallChildIndex = rightIndex;
98 | }
99 | }
100 |
101 | if (compare(heap.get(smallChildIndex), heap.get(j)) >= 0) {
102 | break;
103 | }
104 |
105 | swap(j, smallChildIndex);
106 | j = smallChildIndex;
107 | }
108 | }
109 |
110 | @Override
111 | public int size() {
112 | return heap.size();
113 | }
114 |
115 | @Override
116 | public Entry min() {
117 | if (heap.isEmpty()) {
118 | return null;
119 | }
120 |
121 | return heap.get(0);
122 | }
123 |
124 | @Override
125 | public Entry insert(K key, V value) throws IllegalArgumentException {
126 | checkKey(key);
127 | Entry newest = new PQEntry<>(key, value);
128 | heap.add(newest);
129 | upHeap(heap.size() - 1);
130 | return newest;
131 | }
132 |
133 | @Override
134 | public Entry removeMin() {
135 | if (heap.isEmpty()) {
136 | return null;
137 | }
138 |
139 | Entry temp = heap.get(0);
140 | swap(0, heap.size() - 1);
141 | heap.remove(heap.size() - 1);
142 | downHeap(0);
143 | return temp;
144 | }
145 |
146 | /**
147 | * Performs a bottom-up construction of the heap in linear time.
148 | */
149 | protected void heapify() {
150 | int startIndex = parent(size() - 1); // start at PARENT of last entry
151 | for (int j = startIndex; j >= 0; j--) { // loop until processing the root
152 | downHeap(j);
153 | }
154 | }
155 |
156 | }
157 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter09/PriorityQueue.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter09;
2 |
3 | /**
4 | * Interface for the priority queue ADT.
5 | *
6 | * @author Rogerio J. Gentil
7 | * @param
8 | * @param
9 | */
10 | public interface PriorityQueue {
11 |
12 | int size();
13 |
14 | boolean isEmpty();
15 |
16 | Entry insert(K key, V value) throws IllegalArgumentException;
17 |
18 | Entry min();
19 |
20 | Entry removeMin();
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter09/PriorityQueueUtils.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter09;
2 |
3 | import rogeriogentil.data.structures.chapter07.PositionalList;
4 |
5 | /**
6 | *
7 | * @author Rogerio J. Gentil
8 | * @param
9 | */
10 | public class PriorityQueueUtils {
11 |
12 | /**
13 | * Sorts sequence using initially empty priority queue to produce the order.
14 | *
15 | * @param
16 | * @param sequence
17 | * @param priorityQueue
18 | */
19 | public static void pqSort(PositionalList sequence, PriorityQueue priorityQueue) {
20 | int n = sequence.size();
21 |
22 | for (int i = 0; i < n; i++) {
23 | E element = sequence.remove(sequence.first());
24 | priorityQueue.insert(element, null); // element is key; null value
25 | }
26 |
27 | for (int i = 0; i < n; i++) {
28 | E element = priorityQueue.removeMin().getKey();
29 | sequence.addLast(element); // the smallest key in Priority Queye is next placed in Sequence
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/rogeriogentil/data/structures/chapter09/SortedPriorityQueue.java:
--------------------------------------------------------------------------------
1 | package rogeriogentil.data.structures.chapter09;
2 |
3 | import java.util.Comparator;
4 | import rogeriogentil.data.structures.chapter07.LinkedPositionalList;
5 | import rogeriogentil.data.structures.chapter07.Position;
6 |
7 | /**
8 | *
9 | * @author Rogerio J. Gentil
10 | * @param key
11 | * @param