This commit is contained in:
k0rrluna 2025-04-29 17:51:52 +03:00
parent 9e95d7d514
commit 86ef6a2f43
21 changed files with 1272 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,48 @@
/**
An interface that describes the operations of a bag of objects.
@author Frank M. Carrano
@version 4.0
*/
public interface BagInterface<T>
{
/** Gets the current number of entries in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize();
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty();
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True if the addition is successful, or false if not. */
public boolean add(T newEntry);
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal.
was successful, or null. */
public T remove();
/** Removes one occurrence of a given entry from this bag.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry);
/** Removes all entries from this bag. */
public void clear();
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry);
/** Tests whether this bag contains a given entry.
@param anEntry The entry to locate.
@return True if the bag contains anEntry, or false if not. */
public boolean contains(T anEntry);
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in the bag.
Note: If the bag is empty, the returned array is empty. */
public T[] toArray();
} // end BagInterface

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,132 @@
/**
A class of bags whose entries are stored in a chain of linked nodes.
The bag is never full.
@author Frank M. Carrano
@version 4.0
*/
public final class LinkedBag<T> implements BagInterface<T>
{
private Node firstNode; // Reference to first node
private int numberOfEntries;
public LinkedBag()
{
firstNode = null;
numberOfEntries = 0;
} // end default constructor
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True. */
public boolean add(T newEntry) // OutOfMemoryError possible
{
// Add to beginning of chain:
Node newNode = new Node(newEntry);
newNode.next = firstNode; // Make new node reference rest of chain
// (firstNode is null if chain is empty)
firstNode = newNode; // New node is at beginning of chain
numberOfEntries++;
return true;
} // end add
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in this bag. */
public T[] toArray()
{
// The cast is safe because the new array contains null entries.
@SuppressWarnings("unchecked")
T[] result = (T[])new Object[numberOfEntries]; // Unchecked cast
int index = 0;
Node currentNode = firstNode;
while ((index < numberOfEntries) && (currentNode != null))
{
result[index] = currentNode.data;
index++;
currentNode = currentNode.next;
} // end while
return result;
// Note: The body of this method could consist of one return statement,
// if you call Arrays.copyOf
} // end toArray
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty()
{
return numberOfEntries == 0;
} // end isEmpty
/** Gets the number of entries currently in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize()
{
return numberOfEntries;
} // end getCurrentSize
// STUBS:
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal
was successful, or null. */
public T remove()
{
T top = firstNode.data;
firstNode = firstNode.next;
numberOfEntries--;
return top;
} // end remove
/** Removes one occurrence of a given entry from this bag.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false otherwise. */
public boolean remove(T anEntry)
{
return false; // STUB
} // end remove
/** Removes all entries from this bag. */
public void clear()
{
// STUB
} // end clear
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry)
{
return 0; // STUB
} // end getFrequencyOf
/** Tests whether this bag contains a given entry.
@param anEntry The entry to locate.
@return True if the bag contains anEntry, or false otherwise. */
public boolean contains(T anEntry)
{
return false; // STUB
} // end contains
private class Node
{
private T data; // Entry in bag
private Node next; // Link to next node
private Node(T dataPortion)
{
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
} // end Node
} // end LinkedBag1

View File

@ -0,0 +1,85 @@
/** A test of the methods add, toArray, isEmpty, and getCurrentSize,
as defined in the first draft of the class LinkedBag.
@author Frank M. Carrano
@version 4.0
*/
public class LinkedBagDemo
{
public static void main(String[] args)
{
System.out.println("Creating an empty bag.");
BagInterface<String> aBag = new LinkedBag<>();
testIsEmpty(aBag, true);
displayBag(aBag);
String[] contentsOfBag = {"A", "D", "B", "A", "C", "A", "D"};
testAdd(aBag, contentsOfBag);
testIsEmpty(aBag, false);
} // end main
// Tests the method isEmpty.
// Precondition: If the bag is empty, the parameter empty should be true;
// otherwise, it should be false.
private static void testIsEmpty(BagInterface<String> bag, boolean empty)
{
System.out.print("\nTesting isEmpty with ");
if (empty)
System.out.println("an empty bag:");
else
System.out.println("a bag that is not empty:");
System.out.print("isEmpty finds the bag ");
if (empty && bag.isEmpty())
System.out.println("empty: OK.");
else if (empty)
System.out.println("not empty, but it is: ERROR.");
else if (!empty && bag.isEmpty())
System.out.println("empty, but it is not empty: ERROR.");
else
System.out.println("not empty: OK.");
} // end testIsEmpty
// Tests the method add.
private static void testAdd(BagInterface<String> aBag, String[] content)
{
System.out.print("Adding the following " + content.length +
" strings to the bag: ");
for (int index = 0; index < content.length; index++)
{
if (aBag.add(content[index]))
System.out.print(content[index] + " ");
else
System.out.print("\nUnable to add " + content[index] +
" to the bag.");
} // end for
System.out.println();
displayBag(aBag);
} // end testAdd
// Tests the method toArray while displaying the bag.
private static void displayBag(BagInterface<String> aBag)
{
System.out.println("The bag contains the following string(s):");
Object[] bagArray = aBag.toArray();
for (int index = 0; index < bagArray.length; index++)
{
System.out.print(bagArray[index] + " ");
} // end for
System.out.println();
} // end displayBag
} // end LinkedBagDemo1
/*
Creating an empty bag.
Testing isEmpty with an empty bag:
isEmpty finds the bag empty: OK.
The bag contains the following string(s):
Adding the following 7 strings to the bag: A D B A C A D
The bag contains the following string(s):
D A C A B D A
Testing isEmpty with a bag that is not empty:
isEmpty finds the bag not empty: OK.
*/

View File

@ -0,0 +1,149 @@
/**
A class that implements the ADT queue by using an expandable
circular array with one unused location.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public final class ArrayQueue<T> implements QueueInterface<T>
{
private T[] queue; // Circular array of queue entries and one unused location
private int frontIndex;
private int backIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayQueue()
{
this(DEFAULT_CAPACITY);
} // end default constructor
public ArrayQueue(int initialCapacity)
{
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempQueue = (T[]) new Object[initialCapacity + 1];
queue = tempQueue;
frontIndex = 0;
backIndex = initialCapacity;
initialized = true;
} // end constructor
public void enqueue(T newEntry)
{
checkInitialization();
ensureCapacity();
backIndex = (backIndex + 1) % queue.length;
queue[backIndex] = newEntry;
} // end enqueue
public T getFront()
{
checkInitialization();
if (isEmpty())
throw new EmptyQueueException();
else
return queue[frontIndex];
} // end getFront
public T dequeue()
{
checkInitialization();
if (isEmpty())
throw new EmptyQueueException();
else
{
T front = queue[frontIndex];
queue[frontIndex] = null;
frontIndex = (frontIndex + 1) % queue.length;
return front;
} // end if
} // end dequeue
// Doubles the size of the array queue if it is full
// Precondition: checkInitialization has been called.
private void ensureCapacity()
{
if (frontIndex == ((backIndex + 2) % queue.length)) // if array is full,
{ // double size of array
T[] oldQueue = queue;
int oldSize = oldQueue.length;
int newSize = 2 * oldSize;
checkCapacity(newSize);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempQueue = (T[]) new Object[2 * oldSize];
queue = tempQueue;
for (int index = 0; index < oldSize - 1; index++)
{
queue[index] = oldQueue[frontIndex];
frontIndex = (frontIndex + 1) % oldSize;
} // end for
frontIndex = 0;
backIndex = oldSize - 2;
} // end if
} // end ensureCapacity
public boolean isEmpty()
{
return frontIndex == ((backIndex + 1) % queue.length);
} // end isEmpty
// Throws an exception if this object is not initialized.
private void checkInitialization()
{
if (!initialized)
{
throw new SecurityException ("ArrayQueue object is not initialized properly.");
}
}
// Throws an exception if the client requests a capacity that is too large.
private void checkCapacity(int capacity)
{
if (capacity > MAX_CAPACITY)
{
throw new IllegalStateException("Attempt to create a queue " +
"whose capacity exceeds " +
"allowed maximum.");
}
}
// Question 3, Chapter 11
public void clear()
{
checkInitialization();
if (!isEmpty())
{ // deallocates only the used portion
for (int index = frontIndex; index != backIndex; index = (index + 1) % queue.length)
{
queue[index] = null;
}
queue[backIndex] = null;
}
frontIndex = 0;
backIndex = queue.length - 1;
}
/*
// Question 4, Chapter 11
public void clear()
{
while (!isEmpty())
{
dequeue();
}
}
*/
} // end ArrayQueue

View File

@ -0,0 +1,13 @@
/** A class of runtime exceptions thrown when an attempt is made
to access or remove the front of a queue. @author Frank M. Carrano
*/
public class EmptyQueueException extends RuntimeException {
public EmptyQueueException() {
this(null);
} // end default
public EmptyQueueException(String message) {
super(message);
} // end constructor
} // end EmptyQueueException

BIN
DataLabs/lab5/Lab5.docx Normal file

Binary file not shown.

View File

@ -0,0 +1,101 @@
/**
A class that implements the ADT queue by using a chain of nodes
that has both head and tail references.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public final class LinkedQueue<T> implements QueueInterface<T>
{
private Node firstNode; // References node at front of queue
private Node lastNode; // References node at back of queue
public LinkedQueue()
{
firstNode = null;
lastNode = null;
} // end default constructor
public void enqueue(T newEntry)
{
Node newNode = new Node(newEntry, null);
if (isEmpty())
firstNode = newNode;
else
lastNode.setNextNode(newNode);
lastNode = newNode;
} // end enqueue
public T getFront()
{
if (isEmpty())
throw new EmptyQueueException();
else
return firstNode.getData();
} // end getFront
public T dequeue()
{
T front = getFront(); // Might throw EmptyQueueException
assert firstNode != null;
firstNode.setData(null);
firstNode = firstNode.getNextNode();
if (firstNode == null)
lastNode = null;
return front;
} // end dequeue
public boolean isEmpty()
{
return (firstNode == null) && (lastNode == null);
} // end isEmpty
public void clear()
{
firstNode = null;
lastNode = null;
} // end clear
private class Node
{
private T data; // Entry in queue
private Node next; // Link to next node
private Node(T dataPortion)
{
data = dataPortion;
next = null;
} // end constructor
private Node(T dataPortion, Node linkPortion)
{
data = dataPortion;
next = linkPortion;
} // end constructor
private T getData()
{
return data;
} // end getData
private void setData(T newData)
{
data = newData;
} // end setData
private Node getNextNode()
{
return next;
} // end getNextNode
private void setNextNode(Node nextNode)
{
next = nextNode;
} // end setNextNode
} // end Node
} // end LinkedQueue

View File

@ -0,0 +1,29 @@
/**
An interface for the ADT queue.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public interface QueueInterface<T>
{
/** Adds a new entry to the back of this queue.
@param newEntry An object to be added. */
public void enqueue(T newEntry);
/** Removes and returns the entry at the front of this queue.
@return The object at the front of the queue.
@throws EmptyQueueException if the queue is empty before the operation. */
public T dequeue();
/** Retrieves the entry at the front of this queue.
@return The object at the front of the queue.
@throws EmptyQueueException if the queue is empty. */
public T getFront();
/** Detects whether this queue is empty.
@return True if the queue is empty, or false otherwise. */
public boolean isEmpty();
/** Removes all entries from this queue. */
public void clear();
} // end QueueInterface

View File

@ -0,0 +1,29 @@
public class StockLedger {
private QueueInterface<StockPurchase> ledger;
public StockLedger() {
ledger = new LinkedQueue<>();
}
public void buy(int sharesBought, double pricePerShare){
while(!SharesBought) {
StockPurchase purchase = new StockPurchase(pricePerShare);
ledger.enqueue(purchase);
sharesBought--;
}
}
public double sell(int sharesSold, double pricePerShare){
double saleAmount = sharesSold*pricePerShare;
double totalCost = 0;
while (!sharesSold){
StockPurchase share = ledger.dequeue();
double shareCost = share.getCostPerShare();
totalCost += shareCost;
sharesSold--;
}
return saleAmount - totalCost;
}
}

View File

@ -0,0 +1,276 @@
package dictionary;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
A class that implements the ADT dictionary by using a resizable array.
The dictionary is unsorted and has distinct search keys.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public class ArrayDictionary<K, V> implements DictionaryInterface<K, V>
{
protected Entry<K, V>[] dictionary; // Array of unsorted entries
protected int numberOfEntries;
private boolean initialized = false;
private final static int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;
public ArrayDictionary()
{
this(DEFAULT_CAPACITY); // Call next constructor
} // end default constructor
public ArrayDictionary(int initialCapacity)
{
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
Entry<K, V>[] tempDictionary = (Entry<K, V>[])new Entry[initialCapacity];
dictionary = tempDictionary;
numberOfEntries = 0;
initialized = true;
} // end constructor
public V add(K key, V value)
{
checkInitialization();
if ((key == null) || (value == null))
throw new IllegalArgumentException("Cannot add null to a dictionary.");
else
{
V result = null;
int keyIndex = locateIndex(key);
if (keyIndex < numberOfEntries)
{
// Key found, return and replace entry's value
result = dictionary[keyIndex].getValue(); // Get old value
dictionary[keyIndex].setValue(value); // Replace value
}
else // Key not found; add new entry to dictionary
{
// Add at end of array
dictionary[numberOfEntries] = new Entry<>(key, value);
numberOfEntries++;
ensureCapacity(); // Ensure enough room for next add
} // end if
return result;
} // end if
} // end add
// Returns the array index of the entry that contains key, or
// returns numberOfEntries if no such entry exists.
private int locateIndex(K key)
{
// Sequential search
int index = 0;
while ( (index < numberOfEntries) && !key.equals(dictionary[index].getKey()) )
index++;
return index;
} // end locateIndex
public V remove(K key)
{
checkInitialization();
V result = null;
int keyIndex = locateIndex(key);
if (keyIndex < numberOfEntries)
{
// Key found; remove entry and return its value
result = dictionary[keyIndex].getValue();
dictionary[keyIndex] = dictionary[numberOfEntries - 1];
dictionary[numberOfEntries - 1] = null;
numberOfEntries--;
} // end if
// Else result is null
return result;
} // end remove
public V getValue(K key)
{
checkInitialization();
V result = null;
int keyIndex = locateIndex(key);
if (keyIndex < numberOfEntries)
{
result = dictionary[keyIndex].getValue(); // Key found; return value
} // end if
return result;
} // end getValue
public boolean contains(K key)
{
return getValue(key) != null;
} // end contains
public boolean isEmpty()
{
return numberOfEntries == 0;
} // end isEmpty
public int getSize()
{
return numberOfEntries;
} // end getSize
public final void clear()
{
checkInitialization();
// Clear entries but retain array; no need to create a new array
for (int index = 0; index < numberOfEntries; index++)
dictionary[index] = null;
numberOfEntries = 0;
} // end clear
protected void ensureCapacity()
{
if (numberOfEntries >= dictionary.length)
{
int newCapacity = 2 * dictionary.length;
checkCapacity(newCapacity);
dictionary = Arrays.copyOf(dictionary, newCapacity);
} // end if
} // end ensureCapacity
// Throws an exception if this object is not initialized.
protected void checkInitialization()
{
if (!initialized)
{
throw new SecurityException ("ArrayDictionary object is not initialized properly.");
}
}
// Throws an exception if the client requests a capacity that is too large.
protected void checkCapacity(int capacity)
{
if (capacity > MAX_CAPACITY)
{
throw new IllegalStateException("Attempt to create a HashedDictionary " +
"whose capacity exceeds " +
"allowed maximum.");
}
}
public Iterator<K> getKeyIterator()
{
return new KeyIterator();
} // end getKeyIterator
public Iterator<V> getValueIterator()
{
return new ValueIterator();
} // end getValueIterator
protected class Entry<S, T>
{
private S key;
private T value;
protected Entry(S searchKey, T dataValue)
{
key = searchKey;
value = dataValue;
} // end constructor
protected S getKey()
{
return key;
} // end getKey
protected T getValue()
{
return value;
} // end getValue
protected void setValue(T dataValue)
{
value = dataValue;
} // end setValue
} // end Entry
// Since iterators implement Iterator, methods must be public.
// Same as SortedArrayDictionary.
private class KeyIterator implements Iterator<K>
{
private int currentIndex;
private KeyIterator()
{
currentIndex = 0;
} // end default constructor
public boolean hasNext()
{
return currentIndex < numberOfEntries;
} // end hasNext
public K next()
{
K result = null;
if (hasNext())
{
Entry<K,V> currentEntry = dictionary[currentIndex];
result = currentEntry.getKey();
currentIndex++;
}
else
{
throw new NoSuchElementException();
} // end if
return result;
} // end next
public void remove()
{
throw new UnsupportedOperationException();
} // end remove
} // end KeyIterator
private class ValueIterator implements Iterator<V>
{
private int currentIndex;
private ValueIterator()
{
currentIndex = 0;
} // end default constructor
public boolean hasNext()
{
return currentIndex < numberOfEntries;
} // end hasNext
public V next()
{
V result = null;
if (hasNext())
{
Entry<K,V> currentEntry = dictionary[currentIndex];
result = currentEntry.getValue();
currentIndex++;
}
else
{
throw new NoSuchElementException();
} // end if
return result;
} // end next
public void remove()
{
throw new UnsupportedOperationException();
} // end remove
} // end getValueIterator
} // end dictionary.ArrayDictionary

View File

@ -0,0 +1,60 @@
package dictionary;
import java.util.Iterator;
/**
An interface for a dictionary with distinct search keys.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public interface DictionaryInterface<K, V>
{
/** Adds a new entry to this dictionary. If the given search key already
exists in the dictionary, replaces the corresponding value.
@param key An object search key of the new entry.
@param value An object associated with the search key.
@return Either null if the new entry was added to the dictionary
or the value that was associated with key if that value
was replaced. */
public V add(K key, V value);
/** Removes a specific entry from this dictionary.
@param key An object search key of the entry to be removed.
@return Either the value that was associated with the search key
or null if no such object exists. */
public V remove(K key);
/** Retrieves from this dictionary the value associated with a given
search key.
@param key An object search key of the entry to be retrieved.
@return Either the value that is associated with the search key
or null if no such object exists. */
public V getValue(K key);
/** Sees whether a specific entry is in this dictionary.
@param key An object search key of the desired entry.
@return True if key is associated with an entry in the dictionary. */
public boolean contains(K key);
/** Creates an iterator that traverses all search keys in this dictionary.
@return An iterator that provides sequential access to the search
keys in the dictionary. */
public Iterator<K> getKeyIterator();
/** Creates an iterator that traverses all values in this dictionary.
@return An iterator that provides sequential access to the values
in this dictionary. */
public Iterator<V> getValueIterator();
/** Sees whether this dictionary is empty.
@return True if the dictionary is empty. */
public boolean isEmpty();
/** Gets the size of this dictionary.
@return The number of entries (key-value pairs) currently
in the dictionary. */
public int getSize();
/** Removes all entries from this dictionary. */
public void clear();
} // end dictionary.DictionaryInterface

BIN
DataLabs/lab6/Lab6.docx Normal file

Binary file not shown.

85
DataLabs/lab6/Name.java Normal file
View File

@ -0,0 +1,85 @@
package dictionary;
/**
A class that represents a person's name.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public class Name implements Comparable<Name> {
private String first; // First name
private String last; // Last name
public Name()
{
} // end default constructor
public Name(String firstName, String lastName)
{
first = firstName;
last = lastName;
} // end constructor
public void setName(String firstName, String lastName)
{
setFirst(firstName);
setLast(lastName);
} // end setName
public String getName()
{
return toString();
} // end getName
public void setFirst(String firstName)
{
first = firstName;
} // end setFirst
public String getFirst()
{
return first;
} // end getFirst
public void setLast(String lastName)
{
last = lastName;
} // end setLast
public String getLast()
{
return last;
} // end getLast
public void giveLastNameTo(Name aName)
{
aName.setLast(last);
} // end giveLastNameTo
public String toString()
{
return first + " " + last;
} // end toString
@Override
public int compareTo(Name name) {
int lastCmp = last.compareTo(name.last);
return (lastCmp != 0 ? lastCmp : first.compareTo(name.first));
}
@Override
public boolean equals(Object name) {
// If the object is compared with itself then return true
if (name == this) {
return true;
}
/* Check if o is an instance of Complex or not
"null instanceof [type]" also returns false */
if (!(name instanceof Name)) {
return false;
}
return compareTo( (Name)name ) == 0;
}
} // end Name

View File

@ -0,0 +1,104 @@
package dictionary;
/**
A class that implements the ADT dictionary by using a resizable sorted array.
The dictionary has distinct search keys.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public class SortedArrayDictionary<K extends Comparable<? super K>, V>
extends ArrayDictionary<K, V> implements DictionaryInterface<K, V>
{
/* < Constructors analogous to those in Listing 20-1. >
. . . */
public SortedArrayDictionary()
{
super(); // Call next constructor
} // end default constructor
public SortedArrayDictionary(int initialCapacity)
{
super(initialCapacity);
} // end constructor
// 20.11
/** Precondition: key and value are not null. */
public V add(K key, V value)
{
checkInitialization();
if ((key == null) || (value == null))
throw new IllegalArgumentException("Cannot add null to a dictionary.");
else
{
V result = null;
int keyIndex = locateIndex(key);
if ( (keyIndex < numberOfEntries) &&
key.equals(dictionary[keyIndex].getKey()) )
{
// Key found, return and replace entry's value
result = dictionary[keyIndex].getValue(); // Old value
dictionary[keyIndex].setValue(value); // Replace value
}
else // Key not found; add new entry to dictionary
{
makeRoom(keyIndex); // Make room for new entry
dictionary[keyIndex] = new Entry<K, V>(key, value); // Insert new entry in array
numberOfEntries++;
ensureCapacity(); // Ensure enough room for next add
} // end if
return result;
} // end if
} // end add
/* < Implementations of other methods in dictionary.DictionaryInterface. >
. . . */
// 20.12
// Returns the index of either the entry that contains key or
// the location that should contain key, if no such entry exists.
private int locateIndex(K key)
{
// Search until you either find an entry containing key or
// pass the point where it should be
int index = 0;
while ( (index < numberOfEntries) &&
key.compareTo(dictionary[index].getKey()) > 0 )
{
index++;
} // end while
return index;
} // end locateIndex
// Makes room for a new entry at a given index by shifting
// array entries towards the end of the array.
// Precondition: keyIndex is valid; list length is old length.
private void makeRoom(int keyIndex)
{
assert (keyIndex >= 1) && (keyIndex <= numberOfEntries + 1);
int newIndex = keyIndex;
int lastIndex = numberOfEntries;
// Move each entry to next higher index, starting at end of
// dictionary and continuing until the entry at newIndex is moved
for (int index = lastIndex; index >= newIndex; index--)
dictionary[index + 1] = dictionary[index];
} // end makeRoom
// Removes an entry at a given index by shifting array
// entries toward the entry to be removed.
private void removeArrayEntry(int keyIndex)
{
// . . . To be implemented
} // end removeArrayEntry
} // end dictionary.SortedArrayDictionary

View File

@ -0,0 +1,13 @@
import java.util.Iterator;
import java.util.Scanner;
public class TelephoneDirectory
{
private DictionaryInterface<Name, String> phoneBook;
public TelephoneDirectory()
{
//phoneBook = new SortedArrayDictionary<>();
phoneBook = new SortedLinkedDictionary<>(); //Currently Linked Directory
} // end default constructor

5
DataLabs/lab6/data.txt Normal file
View File

@ -0,0 +1,5 @@
Ali Koc 1234
Mehmet Sezgin 4567
Ayse Kahraman 8765
Ela Bekir 324242
Mehmet Sezgin 1111

21
test/ListInterface.java Normal file
View File

@ -0,0 +1,21 @@
public interface ListInterface<T>{
public void add(T newEntry);
public void add(int newPosition, T newEntry);
public T remove(int givenPosition);
public void clear();
public T replace(int givenPosition, T newEntry);
public T getEntry(int givenPosition);
public T[] toArray();
public boolean contains(T anEntry);
public int getLenght();
public boolean isEmpty();
}

122
test/Llist.java Normal file
View File

@ -0,0 +1,122 @@
public class LList<T> implements ListInterface<T>{
private Node firstNode;
private int numOfEntries;
public LList () {
initializeDataFields();
}
public void clear () {
initializeDataFields();
}
public void add (T newEntry) {
Node newNode = new Node(newEntry);
if (isEmpty) {
firstNode = newNode;
} else {
lastNode = getNodeAt(numOfEntries);
lastNode.setNextNode(newNode);
}
numOfEntries++;
}
public void add (int newPos, T newEntry) {
if((newPos < numOfEntries) && (newPos > 0)) {
Node newNode = new Node(newEntry);
if (newPos == 1) {
newNode.setNextNode(firstNode);
firstNode = newNode;
} else {
Node nodeBefore = getNodeAt(newPos - 1);
Node nodeAfter = nodeBefore.getNextNode();
newNode.setNextNode(nodeAfter);
nodeBefore.setNextNode(newNode);
}
numOfEntries++;
} else {
throw new e("Nope");
}
}
public boolean isEmpty(){
return ((numOfEntries > 0));
}
public T[] toArray () {
@SuppressWarnings("unchecked")
T[] result = (T[])new Object[numOfEntries];
Node currentNode = firstNode;
for (int i = 0; i < numOfEntries; i++) {
result[i] = currentNode.getData();
currentNode = currentNode.getNextNode();
}
return result;
}
public T remove (int givenPos) {
T result = null;
if (givenPos <= numOfEntries && givenPos > 0) {
if (!isEmpty()) {
if (givenPos == 1) {
result = firstNode.getData();
firstNode = firstNode.getNextNode();
} else {
Node nodeBefore = getNodeAt(givenPos - 1);
Node nodeToRemove = nodeBefore.getNextNode();
result = nodeToRemove.getData();
Node nodeAfter = nodeToRemove.getNextNode();
nodeBefore.setNextNode(nodeAfter);
}
numOfEntries--;
return result;
} else {
throw new e("NOOO");
}
}
}
public T replace (int givenPos, T newEntry) {
if(givenPos > 0 && givenPos <= numOfEntries) {
Node desiredNode = getNodeAt(givenPos);
T originalEntry = desiredNode.getData();
desiredNode.setData(newEntry);
return originalEntry;
} else {
throw new e("NOOOOOO");
}
}
// Start from node
private class Node {
private T data;
private Node next;
private Node (T dataPortion) {
this(dataPortion, null);
}
private Node (T dataPortion, Node nextNode) {
data = dataPortion;
next = nextNode;
}
private T getData () {
return data;
}
private void setData (T newData) {
data = newData;
}
private Node getNextNode () {
return next;
}
private Node setNextNode (Node nextNode) {
next = NextNode;
}
}
}