removed duplciated data-structures

This commit is contained in:
Christian Bender 2018-07-25 16:37:10 +02:00
parent 89b94a8f52
commit c86ba856a8
52 changed files with 75 additions and 30618 deletions

View File

@ -1,126 +0,0 @@
package Bags;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Collection which does not allow removing elements (only collect and iterate)
*
* @param <Element> - the generic type of an element in this bag
*/
public class Bag<Element> implements Iterable<Element> {
private Node<Element> firstElement; // first element of the bag
private int size; // size of bag
private static class Node<Element> {
private Element content;
private Node<Element> nextElement;
}
/**
* Create an empty bag
*/
public Bag() {
firstElement = null;
size = 0;
}
/**
* @return true if this bag is empty, false otherwise
*/
public boolean isEmpty() {
return firstElement == null;
}
/**
* @return the number of elements
*/
public int size() {
return size;
}
/**
* @param element - the element to add
*/
public void add(Element element) {
Node<Element> oldfirst = firstElement;
firstElement = new Node<>();
firstElement.content = element;
firstElement.nextElement = oldfirst;
size++;
}
/**
* Checks if the bag contains a specific element
*
* @param element which you want to look for
* @return true if bag contains element, otherwise false
*/
public boolean contains(Element element) {
Iterator<Element> iterator = this.iterator();
while(iterator.hasNext()) {
if (iterator.next().equals(element)) {
return true;
}
}
return false;
}
/**
* @return an iterator that iterates over the elements in this bag in arbitrary order
*/
public Iterator<Element> iterator() {
return new ListIterator<>(firstElement);
}
@SuppressWarnings("hiding")
private class ListIterator<Element> implements Iterator<Element> {
private Node<Element> currentElement;
public ListIterator(Node<Element> firstElement) {
currentElement = firstElement;
}
public boolean hasNext() {
return currentElement != null;
}
/**
* remove is not allowed in a bag
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
public Element next() {
if (!hasNext())
throw new NoSuchElementException();
Element element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
/**
* main-method for testing
*/
public static void main(String[] args) {
Bag<String> bag = new Bag<>();
bag.add("1");
bag.add("1");
bag.add("2");
System.out.println("size of bag = " + bag.size());
for (String s : bag) {
System.out.println(s);
}
System.out.println(bag.contains(null));
System.out.println(bag.contains("1"));
System.out.println(bag.contains("3"));
}
}

View File

@ -1,124 +0,0 @@
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class CircularBuffer {
private char[] _buffer;
public final int _buffer_size;
private int _write_index = 0;
private int _read_index = 0;
private AtomicInteger _readable_data = new AtomicInteger(0);
public CircularBuffer(int buffer_size) {
if(!IsPowerOfTwo(buffer_size)) {
throw new IllegalArgumentException();
}
this._buffer_size = buffer_size;
_buffer = new char[buffer_size];
}
private boolean IsPowerOfTwo(int i) {
return (i & (i - 1)) == 0;
}
private int getTrueIndex(int i) {
return i % _buffer_size;
}
public Character readOutChar() {
Character result = null;
//if we have data to read
if(_readable_data.get() > 0) {
result = new Character(_buffer[getTrueIndex(_read_index)]);
_readable_data.decrementAndGet();
_read_index++;
}
return result;
}
public boolean writeToCharBuffer(char c) {
boolean result = false;
//if we can write to the buffer
if(_readable_data.get() < _buffer_size) {
//write to buffer
_buffer[getTrueIndex(_write_index)] = c;
_readable_data.incrementAndGet();
_write_index++;
result = true;
}
return result;
}
private static class TestWriteWorker implements Runnable {
String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
Random _random = new Random();
CircularBuffer _buffer;
public TestWriteWorker(CircularBuffer cb) {
this._buffer = cb;
}
private char getRandomChar() {
return _alphabet.charAt(_random.nextInt(_alphabet.length()));
}
public void run() {
while(!Thread.interrupted()) {
if(!_buffer.writeToCharBuffer(getRandomChar())){
Thread.yield();
try{
Thread.sleep(10);
} catch (InterruptedException e) {
return;
}
}
}
}
}
private static class TestReadWorker implements Runnable {
CircularBuffer _buffer;
public TestReadWorker(CircularBuffer cb) {
this._buffer = cb;
}
public void run() {
System.out.println("Printing Buffer:");
while(!Thread.interrupted()) {
Character c = _buffer.readOutChar();
if(c != null) {
System.out.print(c.charValue());
} else {
Thread.yield();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println();
return;
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
int buffer_size = 1024;
//create circular buffer
CircularBuffer cb = new CircularBuffer(buffer_size);
//create threads that read and write the buffer.
Thread write_thread = new Thread(new TestWriteWorker(cb));
Thread read_thread = new Thread(new TestReadWorker(cb));
read_thread.start();
write_thread.start();
//wait some amount of time
Thread.sleep(10000);
//interrupt threads and exit
write_thread.interrupt();
read_thread.interrupt();
}
}

View File

@ -1,692 +0,0 @@
/*
* author: Christian Bender
* class: CSVFile
*
* This class implements a data structure for handling of
* CSV-files.
*
* Overview
*
* CSVFile(path : string, seperator : char)
* compiles the CSV-file in the inner data structure.
*
* CSVFile (file : File, seperator : char)
* CSVFile (seperator : char)
*
* compile (row : string, seperator : char) : string
* compiles row in its columns.
*
* isPunctuation (ch : char) : boolean
* check whether ch is a punctuation character.
*
* getElementString(row : int, column : int) : string
* returns the specified element.
*
* getElementDouble(row : int, column : int) : double
* returns the specified element as double.
*
* addRow(row : string) : void
* adds a row to the inner data structure.
* without writing into the CSV-file.
*
* set (row : int, column : int, item : string) : void
* replaces the specified item with a newer.
*
* commit() : void
* writes the added data into CSV-file.
*
* commit(path : String) : void
* commit(file : File ) : void
*
* findRow(key : string) : ArrayList<String>
* returns the searched row otherwise null.
*
* contains(key : string) : boolean
* returns true if a row contains 'key' otherwise false.
*
* getColumn(column : int) : ArrayList<String>
* returns the specified column as ArrayList.
*
* getColumn(key : string) : ArrayList<String>
*
* removeRow(key : string) : void
* purpose removes the specified row at the inner data structure.
*
* removeRow(column : int) : void
*
* updateFile() : void
* overwrites the CSV-file with the current inner data structure.
* removed rows are remove in the CSV-file, too.
*
* updateFile(file : File) : void
*
* getNumberOfRows() : int
* returns the number of rows in CSV-File
* it counts only rows that in the table.
*
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Pattern;
public class CSVFile {
// the actual CSV-content
private ArrayList<ArrayList<String>> table;
// to tracking added rows.
private ArrayList<Integer> trackList;
// notice the seperator
private char seperator;
// notice the path of the CSV-File.
private String pathCSVFile;
/**
* Constructor
*
* @param path
* @param seperator
* @purpose loads the CSV-file and fills the inner table with the data
*/
public CSVFile(String path, char seperator) {
this(new File(path),seperator);
}
/**
*
* @param file
* same constructor different arguments.
*/
public CSVFile(File file, char seperator) {
table = new ArrayList<ArrayList<String>>();
trackList = new ArrayList<Integer>();
pathCSVFile = file.getPath();
this.seperator = seperator;
ArrayList<String> colums = new ArrayList<String>();
if (!file.canRead() || !file.isFile()) {
System.out.println("unable to open file");
System.exit(1);
}
try (BufferedReader br = Files.newBufferedReader(Paths.get(file.getAbsolutePath()))) {
br.lines().forEach(line -> table.add(compile(line, seperator)));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
* @param separator
* @purpose Constructor for empty CSV-File.
*/
public CSVFile(char separator) {
table = new ArrayList<ArrayList<String>>();
trackList = new ArrayList<Integer>();
pathCSVFile = "";
this.seperator = seperator;
}
/**
*
* @param row
* @param sep
* the seperator
* @return ArrayList<String> that contains each column of row.
* @purpose compiles row in its columns.
*
*/
public static ArrayList<String> compile(String row, char sep) {
ArrayList<String> columns = new ArrayList<String>();
int state = 0;
char ch = ' ';
String column = "";
int countQuotes = 0;
for (int i = 0; i < row.length(); i++) {
// fetch next character
ch = row.charAt(i);
switch (state) {
// state 0
case 0:
if (Character.isLetter(ch) || Character.isDigit(ch)) {
state = 1;
column += ch;
} else if (ch == '"') { // catch "
state = 2;
column += ch;
} else if (Character.isWhitespace(ch)) {
state = 0;
}
break;
// state 1
case 1:
if ((Character.isLetter(ch) || Character.isDigit(ch)
|| isPunctuation(ch) || Character.isWhitespace(ch))
&& (ch != sep)) {
state = 1;
column += ch;
} else if (ch == sep || ch == '\n') {
state = 0;
column = column.trim();
columns.add(column);
column = "";
} else { // error case
throw new RuntimeException("compile: invalid"
+ " character " + ch);
}
break;
// state 2
case 2:
if ((Character.isLetter(ch) || Character.isDigit(ch)
|| Character.isWhitespace(ch) || isPunctuation(ch))
&& (ch != '"')) {
state = 2;
column += ch;
} else if (ch == '"') {
state = 3;
column += ch;
} else { // error case
throw new RuntimeException("compile: invalid"
+ " character " + ch);
}
break;
// state 3
case 3:
if ((Character.isLetter(ch) || Character.isDigit(ch)
|| Character.isWhitespace(ch) || isPunctuation(ch))
&& (ch != '"') && (ch != sep)) {
state = 2;
column += ch;
} else if (ch == ',') {
state = 0;
column = column.trim();
columns.add(column);
column = "";
} else { // error case
throw new RuntimeException("compile: invalid"
+ " character " + ch);
}
}
}
// for adding the remaining column
columns.add(column);
column = "";
return columns;
}
private static Pattern PATTERN_PUNCTUATION = Pattern.compile("\\p{Punct}");
/**
*
* @param ch
* @returns true if ch is punctuation character otherwise false.
*/
public static boolean isPunctuation(char ch) {
return PATTERN_PUNCTUATION.matcher("" + ch).matches();
}
/**
*
* @param row
* @param column
* @return the specific element as string
*/
public String getElementString(int row, int column) {
// check arguments
if (row < table.size() && column < table.get(0).size()) {
return table.get(row).get(column);
} else { // error case
throw new RuntimeException("getElementString: "
+ " arguments out of bound.");
}
}
/**
*
* @param row
* @param column
* @return the specific element as double
* @throws NumberFormatException
*/
public double getElementDouble(int row, int column)
throws NumberFormatException {
// check arguments
if (row < table.size() && column < table.get(0).size()) {
return Double.parseDouble(table.get(row).get(column));
} else { // error case
throw new RuntimeException("getElementString: "
+ " arguments out of bound.");
}
}
/**
*
* @param row
* @purpose adds a row to the inner data structure.
* without writing into the CSV-file.
*/
public void addRow(String row) {
table.add(compile(row, seperator));
// tracking the last item.
trackList.add(table.size() - 1);
}
/**
* @purpose: writes the added data into CSV-file.
*/
public void commit() {
String row = "";
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
pathCSVFile, true)));
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row for the next one
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
* @param path
* @purpose: writes the added data into CSV-file (given path).
*/
public void commit(String path) {
String row = "";
pathCSVFile = path;
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
pathCSVFile, true)));
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
*
* @param file
* @purpose: writes the added data into CSV-file (given path).
*/
public void commit(File file) {
String row = "";
pathCSVFile = file.getPath();
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
file, true)));
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
*
* @param key
* @returns the searched row otherwise null.
*/
public ArrayList<String> findRow(String key) {
ArrayList<String> ans = null;
key = key.trim();
for (int i = 0; i < table.size(); i++) {
for (String item : table.get(i)) {
item = item.trim();
if (item.equals(key)) {
ans = table.get(i);
break;
}
}
}
return ans;
}
/**
*
* @param key
* @returns true if a row contains 'key' otherwise false.
*/
public boolean contains(String key) {
key = key.trim();
for (int i = 0; i < table.size(); i++) {
for (String item : table.get(i)) {
item = item.trim();
if (item.equals(key)) {
return true;
}
}
}
return false;
}
/**
*
* @param n of type integer
* @returns the specified column as ArrayList.
*/
public ArrayList<String> getColumn(int column) {
ArrayList<String> ans = new ArrayList<String>();
if (column < table.get(0).size()) {
for (int i = 0; i < table.size(); i++) {
ans.add(table.get(i).get(column));
}
} else { // error case
throw new RuntimeException("getColumn: column is too large");
}
return ans;
}
/**
*
* @param label of type string
* @returns the specified column at label.
*/
public ArrayList<String> getColumn(String label) {
ArrayList<String> ans = new ArrayList<String>();
int n = table.get(0).indexOf(label);
// check whether label exists.
if (n != -1) {
for (int i = 1; i < table.size(); i++) {
ans.add(table.get(i).get(n));
}
} else { // error case
throw new RuntimeException("getColumn: label " + label
+ " don't exists.");
}
return ans;
}
/**
*
* @param key of type string
* @purpose removes the specified row at the inner data structure.
*/
public void removeRow(String key) {
for (int i = 0; i < table.size(); i++) {
if (table.get(i) != null) {
for (String item : table.get(i)) {
if (item.equals(key)) {
table.set(i,null);
// updates the track list
if (trackList.indexOf(i) != -1) {
trackList.remove(i);
}
}
}
}
}
// removes all null-elements
table.removeAll(Collections.singleton(null));
}
/**
*
* @param n of type integer
* @purpose removes the specified row at the inner data structure.
*/
public void removeRow(int column) {
if (column < table.size()) {
table.set(column, null);
// removes all null-elements
table.removeAll(Collections.singleton(null));
// updates the track list
if (trackList.indexOf(column) != -1) {
trackList.remove(column);
}
} else {
throw new RuntimeException("removeRow: column is too large");
}
}
/**
* overwrites the CSV-file with the current inner data structure.
* removed rows are remove in the CSV-file, too.
*/
public void updateFile() {
String row = "";
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
pathCSVFile)));
// writes the table rows into CSV-file.
for (int i = 0; i < table.size(); i++) {
for (int j = 0; j < table.get(i).size(); j++) {
if (j != 0) {
row += ",";
row += table.get(i).get(j);
} else {
row += table.get(i).get(j);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row for the next one
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
*
* @param file
* overwrites the CSV-file with the current inner data structure.
* removed rows are remove in the CSV-file, too.
*/
public void updateFile(File file) {
String row = "";
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter(
file)));
// writes the table rows into CSV-file.
for (int i = 0; i < table.size(); i++) {
for (int j = 0; j < table.get(i).size(); j++) {
if (j != 0) {
row += ",";
row += table.get(i).get(j);
} else {
row += table.get(i).get(j);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
// writes the tracked rows into CSV-file.
for (int index : trackList) {
for (int i = 0; i < table.get(index).size(); i++) {
if (i != 0) {
row += ",";
row += table.get(index).get(i);
} else {
row += table.get(index).get(i);
}
}
// add newline for next row
row += "\n";
pWriter.write(row);
// clear row
row = "";
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null) {
pWriter.flush();
pWriter.close();
}
}
// remove tracked rows.
trackList.clear();
}
/**
*
* @returns the number of rows in CSV-File
* it counts only rows that in the table.
*/
public int getNumberOfRows() {
return table.size();
}
/**
*
* @param row
* @param column
* @param item
* @purpose replaces the specified item with a newer.
*/
public void set(int row, int column, String item) {
if (row < table.size()) {
if (column < table.get(row).size()) {
table.get(row).set(column, item);
} else {
throw new RuntimeException("set: column is too large!");
}
} else {
throw new RuntimeException("set: row is too large!");
}
}
}

View File

@ -1,133 +0,0 @@
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
public class TestCSVFile {
@Test
public void testConstructor1() {
CSVFile testObj = new CSVFile("testData.csv",',');
assertEquals(testObj.getElementDouble(1, 1),65.78331, 0.001);
assertEquals(testObj.getElementString(1, 1),"65.78331");
assertEquals(testObj.getElementString(0, 1),"\"Height(Inches)\"");
assertEquals(testObj.getNumberOfRows(),25029);
}
@Test
public void testConstructor2() {
CSVFile testObj = new CSVFile(',');
testObj.addRow("1, 65.78331, 112.9925");
testObj.addRow("12, 67.62333, 114.143");
testObj.addRow("6, 68.69784, 123.3024");
// testObj.commit("testData2.csv");
// testObj.commit(new File("testData2.csv"));
}
@Test
public void testConstructor3() {
CSVFile testObj = new CSVFile(new File("testData.csv"),',');
assertEquals(testObj.getElementDouble(1, 1),65.78331, 0.001);
assertEquals(testObj.getElementString(1, 1),"65.78331");
assertEquals(testObj.getElementString(0, 1),"\"Height(Inches)\"");
}
@Test
public void testIsPunctuation() {
assertTrue(CSVFile.isPunctuation(':'));
}
@Test
public void testCompile() {
ArrayList<String> columns = new ArrayList<String>();
columns.add("2");
columns.add("71.51521");
columns.add("136.4873");
assertEquals(CSVFile.compile("2, 71.51521, 136.4873", ','),columns);
columns.clear();
// test successful
columns.add("\"Index\"");
columns.add("\"Height(Inches)\"");
columns.add("\"Weight(Pounds)\"");
assertEquals(CSVFile.compile("\"Index\", \"Height(Inches)\", "
+ "\"Weight(Pounds)\"", ','),columns);
}
@Test
public void testAddRowCommit() {
// CSVFile testObj = new CSVFile("testData.csv",',');
// testObj.addRow("1,1,1");
// testObj.addRow("1,2,3");
// testObj.commit();
// test successful
}
@Test
public void testFindRow() {
CSVFile testObj = new CSVFile("testData.csv",',');
ArrayList<String> columns = new ArrayList<String>();
columns.add("2");
columns.add("71.51521");
columns.add("136.4873");
assertEquals(testObj.findRow("71.51521"),columns);
}
@Test
public void testContains() {
CSVFile testObj = new CSVFile("testData.csv",',');
ArrayList<String> columns = new ArrayList<String>();
columns.add("2");
columns.add("71.51521");
columns.add("136.4873");
assertTrue(testObj.contains("71.51521"));
assertFalse(testObj.contains("9889678"));
}
@Test
public void testGetColumn() {
CSVFile testObj = new CSVFile("testData2.csv",',');
CSVFile testObj2 = new CSVFile("testData3.csv",',');
ArrayList<String> columns = new ArrayList<String>();
columns.add("height");
columns.add("65.78331");
columns.add("67.62333");
assertEquals(testObj.getColumn(1),columns);
columns.clear();
columns.add("65.78331");
columns.add("67.62333");
assertEquals(testObj.getColumn("height"),columns);
columns.clear();
assertEquals(testObj2.getColumn("height"),columns);
}
@Test
public void testRemoving() {
CSVFile testObj = new CSVFile("testData4.csv",',');
//testObj.removeRow("68.69784");
// testObj.removeRow(0);
// testObj.updateFile(new File("testData4.csv"));
// test successful
}
@Test
public void testSet() {
// CSVFile testObj = new CSVFile("testData4.csv",',');
// testObj.set(6, 2, "80");
// testObj.updateFile();
// test succesfull
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +0,0 @@
id, height, width
1, 65.78331, 112.9925
12, 67.62333, 114.143
1 id height width
2 1 65.78331 112.9925
3 12 67.62333 114.143

View File

@ -1 +0,0 @@
id, height, width
1 id height width

View File

@ -1,7 +0,0 @@
1,65.78331,112.9925
2,71.51521,136.4873
3,69.39874,153.0269
4,68.2166,142.3354
5,67.78781,144.2971
7,69.80204,141.4947
8,70.01472,80
1 1 65.78331 112.9925
2 2 71.51521 136.4873
3 3 69.39874 153.0269
4 4 68.2166 142.3354
5 5 67.78781 144.2971
6 7 69.80204 141.4947
7 8 70.01472 80

View File

@ -1,62 +0,0 @@
import java.util.*;
/**
* Implementation of a Breadth First Search
*
* @author Unknown
*
*/
public class BFS{
/**
* The BFS implemented in code to use.
*
* @param a Structure to perform the search on a graph, adjacency matrix etc.
* @param vertices The vertices to use
* @param source The Source
*/
public static void bfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
/* code status
-1 = ready
0 = waiting
1 = processed */
Stack st = new Stack(vertices); //operational stack
st.push(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
System.out.println(st.peek());
int pop=st.peek();
b[pop]=(byte)1; //assigning processed status
st.pop(); //removing head of the queue
for(int i=0;i<vertices;i++){
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
st.push(i);
b[i]=(byte)0; //assigning waiting status
}}}
}
/**
* The main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
byte [][]a=new byte [vertices][vertices];
//initially all elements of a are initialized with value zero
for(int i=0;i<vertices;i++){
int size =in.nextInt();
for(int j=0;j<size;j++){
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
}
}
bfsImplement(a,vertices,source); //function call
in.close();
}
}

View File

@ -1,150 +0,0 @@
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* A class that counts the number of different connected components in a graph
*
* @author Lukas Keul, Florian Mercks
*
*/
class Graph<E extends Comparable<E>> {
class Node {
E name;
public Node(E name) {
this.name = name;
}
}
class Edge {
Node startNode, endNode;
public Edge(Node startNode, Node endNode) {
this.startNode = startNode;
this.endNode = endNode;
}
}
ArrayList<Edge> edgeList;
ArrayList<Node> nodeList;
public Graph() {
edgeList = new ArrayList<Edge>();
nodeList = new ArrayList<Node>();
}
/**
* Adds a new Edge to the graph. If the nodes aren't yet in nodeList, they
* will be added to it.
*
* @param startNode
* the starting Node from the edge
*
* @param endNode
* the ending Node from the edge
*/
public void addEdge(E startNode, E endNode) {
Node start = null, end = null;
for (Node node : nodeList) {
if (startNode.compareTo(node.name) == 0) {
start = node;
}
else if (endNode.compareTo(node.name) == 0) {
end = node;
}
}
if (start == null) {
start = new Node(startNode);
nodeList.add(start);
}
if (end == null) {
end = new Node(endNode);
nodeList.add(end);
}
edgeList.add(new Edge(start, end));
}
/**
* Main method used for counting the connected components. Iterates through
* the array of nodes to do a depth first search to get all nodes of the
* graph from the actual node. These nodes are added to the array
* markedNodes and will be ignored if they are chosen in the nodeList.
*
* @return returns the amount of unconnected graphs
*
*/
public int countGraphs() {
int count = 0;
Set<Node> markedNodes = new HashSet<Node>();
for (Node n : nodeList) {
if (!markedNodes.contains(n)) {
markedNodes.add(n);
markedNodes.addAll(depthFirstSearch(n, new ArrayList<Node>()));
count++;
}
}
return count;
}
/**
* Implementation of depth first search.
*
* @param n
* the actual visiting node
*
* @param visited
* A list of already visited nodes in the depth first search
*
* @return returns a set of visited nodes
*
*/
public ArrayList<Node> depthFirstSearch(Node n, ArrayList<Node> visited) {
visited.add(n);
for (Edge e : edgeList) {
if (e.startNode.equals(n) && !visited.contains(e.endNode)) {
depthFirstSearch(e.endNode, visited);
}
}
return visited;
}
}
public class ConnectedComponent {
public static void main(String[] args) {
Graph graphChars = new Graph();
// Graph 1
graphChars.addEdge('a', 'b');
graphChars.addEdge('a', 'e');
graphChars.addEdge('b', 'e');
graphChars.addEdge('b', 'c');
graphChars.addEdge('c', 'd');
graphChars.addEdge('d', 'a');
graphChars.addEdge('x', 'y');
graphChars.addEdge('x', 'z');
graphChars.addEdge('w', 'w');
Graph graphInts = new Graph();
// Graph 2
graphInts.addEdge(1, 2);
graphInts.addEdge(2, 3);
graphInts.addEdge(2, 4);
graphInts.addEdge(3, 5);
graphInts.addEdge(7, 8);
graphInts.addEdge(8, 10);
graphInts.addEdge(10, 8);
System.out.println("Amount of different char-graphs: " + graphChars.countGraphs());
System.out.println("Amount of different int-graphs: " + graphInts.countGraphs());
}
}

View File

@ -1,63 +0,0 @@
import java.util.*;
/**
* Implementation of a Depth First Search
*
* @author Unknown
*
*/
public class DFS{
/**
* Implementation in code of a DFS
*
* @param a structure to be DFS'ed
* @param vertices The vertices
* @param source The source
*/
public static void dfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
/* code status
-1 = ready
0 = waiting
1 = processed */
Stack st=new Stack(vertices); //operational stack
st.push(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
System.out.println(st.peek());
int pop=st.pop();
b[pop]=(byte)1; //assigning processed status
for(int i=0;i<vertices;i++){
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
st.push(i);
b[i]=(byte)0; //assigning waiting status
}}}
}
/**
* The main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
byte [][]a=new byte [vertices][vertices];
//initially all elements of a are initialized with value zero
for(int i=0;i<vertices;i++){
int size =in.nextInt();
for(int j=0;j<size;j++){
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
}
}
dfsImplement(a,vertices,source); //function call
in.close();
}
}

View File

@ -1,129 +0,0 @@
import java.util.ArrayList;
import java.lang.StringBuilder;
class AdjacencyListGraph<E extends Comparable<E>> {
ArrayList<Vertex> verticies;
public AdjacencyListGraph() {
verticies = new ArrayList<>();
}
private class Vertex {
E data;
ArrayList<Vertex> adjacentVerticies;
public Vertex(E data) {
adjacentVerticies = new ArrayList<>();
this.data = data;
}
public boolean addAdjacentVertex(Vertex to) {
for (Vertex v: adjacentVerticies) {
if (v.data.compareTo(to.data) == 0) {
return false; // the edge already exists
}
}
return adjacentVerticies.add(to); // this will return true;
}
public boolean removeAdjacentVertex(E to) {
// use indexes here so it is possible to
// remove easily without implementing
// equals method that ArrayList.remove(Object o) uses
for (int i = 0; i < adjacentVerticies.size(); i++) {
if (adjacentVerticies.get(i).data.compareTo(to) == 0) {
adjacentVerticies.remove(i);
return true;
}
}
return false;
}
}
/**
* this method removes an edge from the graph between two specified
* verticies
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(E from, E to) {
Vertex fromV = null;
for (Vertex v: verticies) {
if (from.compareTo(v.data) == 0) {
fromV = v;
break;
}
}
if (fromV == null) return false;
return fromV.removeAdjacentVertex(to);
}
/**
* this method adds an edge to the graph between two specified
* verticies
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
*/
public boolean addEdge(E from, E to) {
Vertex fromV = null, toV = null;
for (Vertex v: verticies) {
if (from.compareTo(v.data) == 0) { // see if from vertex already exists
fromV = v;
} else if (to.compareTo(v.data) == 0) { // see if to vertex already exists
toV = v;
}
if (fromV != null && toV != null) break; // both nodes exist so stop searching
}
if (fromV == null) {
fromV = new Vertex(from);
verticies.add(fromV);
}
if (toV == null) {
toV = new Vertex(to);
verticies.add(toV);
}
return fromV.addAdjacentVertex(toV);
}
/**
* this gives a list of verticies in the graph and their adjacencies
*
* @return returns a string describing this graph
*/
public String toString() {
StringBuilder sb = new StringBuilder();
for (Vertex v: verticies) {
sb.append("Vertex: ");
sb.append(v.data);
sb.append("\n");
sb.append("Adjacent verticies: ");
for (Vertex v2: v.adjacentVerticies) {
sb.append(v2.data);
sb.append(" ");
}
sb.append("\n");
}
return sb.toString();
}
}
public class Graphs {
public static void main(String args[]) {
AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>();
assert graph.addEdge(1, 2);
assert graph.addEdge(1, 5);
assert graph.addEdge(2, 5);
assert !graph.addEdge(1, 2);
assert graph.addEdge(2, 3);
assert graph.addEdge(3, 4);
assert graph.addEdge(4, 1);
assert !graph.addEdge(2, 3);
System.out.println(graph);
}
}

View File

@ -1,174 +0,0 @@
// Java program for Kruskal's algorithm to find Minimum Spanning Tree
// of a given connected, undirected and weighted graph
import java.util.*;
import java.lang.*;
import java.io.*;
class Graph
{
// A class to represent a graph edge
class Edge implements Comparable<Edge>
{
int src, dest, weight;
// Comparator function used for sorting edges based on
// their weight
public int compareTo(Edge compareEdge)
{
return this.weight-compareEdge.weight;
}
};
// A class to represent a subset for union-find
class subset
{
int parent, rank;
};
int V, E; // V-> no. of vertices & E->no.of edges
Edge edge[]; // collection of all edges
// Creates a graph with V vertices and E edges
Graph(int v, int e)
{
V = v;
E = e;
edge = new Edge[E];
for (int i=0; i<e; ++i)
edge[i] = new Edge();
}
// A utility function to find set of an element i
// (uses path compression technique)
int find(subset subsets[], int i)
{
// find root and make root as parent of i (path compression)
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
// A function that does union of two sets of x and y
// (uses union by rank)
void Union(subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
// Attach smaller rank tree under root of high rank tree
// (Union by Rank)
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
// If ranks are same, then make one as root and increment
// its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// The main function to construct MST using Kruskal's algorithm
void KruskalMST()
{
Edge result[] = new Edge[V]; // Tnis will store the resultant MST
int e = 0; // An index variable, used for result[]
int i = 0; // An index variable, used for sorted edges
for (i=0; i<V; ++i)
result[i] = new Edge();
// Step 1: Sort all the edges in non-decreasing order of their
// weight. If we are not allowed to change the given graph, we
// can create a copy of array of edges
Arrays.sort(edge);
// Allocate memory for creating V ssubsets
subset subsets[] = new subset[V];
for(i=0; i<V; ++i)
subsets[i]=new subset();
// Create V subsets with single elements
for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}
i = 0; // Index used to pick next edge
// Number of edges to be taken is equal to V-1
while (e < V - 1)
{
// Step 2: Pick the smallest edge. And increment the index
// for next iteration
Edge next_edge = new Edge();
next_edge = edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
// If including this edge does't cause cycle, include it
// in result and increment the index of result for next edge
if (x != y)
{
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}
// print the contents of result[] to display the built MST
System.out.println("Following are the edges in the constructed MST");
for (i = 0; i < e; ++i)
System.out.println(result[i].src+" -- "+result[i].dest+" == "+
result[i].weight);
}
// Driver Program
public static void main (String[] args)
{
/* Let us create following weighted graph
10
0--------1
| \ |
6| 5\ |15
| \ |
2--------3
4 */
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
Graph graph = new Graph(V, E);
// add edge 0-1
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = 10;
// add edge 0-2
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 6;
// add edge 0-3
graph.edge[2].src = 0;
graph.edge[2].dest = 3;
graph.edge[2].weight = 5;
// add edge 1-3
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 15;
// add edge 2-3
graph.edge[4].src = 2;
graph.edge[4].dest = 3;
graph.edge[4].weight = 4;
graph.KruskalMST();
}
}

View File

@ -1,145 +0,0 @@
public class MatrixGraphs {
public static void main(String args[]) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(1, 2);
graph.addEdge(1, 5);
graph.addEdge(2, 5);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
System.out.println(graph);
}
}
class AdjacencyMatrixGraph {
private int _numberOfVertices;
private int _numberOfEdges;
private int[][] _adjacency;
static final int EDGE_EXIST = 1;
static final int EDGE_NONE = 0;
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0);
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
for (int i = 0; i < givenNumberOfVertices; i++) {
for (int j = 0; j < givenNumberOfVertices; j++) {
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
}
}
}
private void setNumberOfVertices(int newNumberOfVertices) {
this._numberOfVertices = newNumberOfVertices;
}
public int numberOfVertices() {
return this._numberOfVertices;
}
private void setNumberOfEdges(int newNumberOfEdges) {
this._numberOfEdges = newNumberOfEdges;
}
public int numberOfEdges() {
return this._numberOfEdges;
}
private void setAdjacency(int[][] newAdjacency) {
this._adjacency = newAdjacency;
}
private int[][] adjacency() {
return this._adjacency;
}
private boolean adjacencyOfEdgeDoesExist(int from, int to) {
return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE);
}
public boolean vertexDoesExist(int aVertex) {
if (aVertex >= 0 && aVertex < this.numberOfVertices()) {
return true;
} else {
return false;
}
}
public boolean edgeDoesExist(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
return (this.adjacencyOfEdgeDoesExist(from, to));
}
return false;
}
/**
* This method adds an edge to the graph between two specified
* vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
*/
public boolean addEdge(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
if (!this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST;
this.setNumberOfEdges(this.numberOfEdges() + 1);
return true;
}
}
return false;
}
/**
* this method removes an edge from the graph between two specified
* vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(int from, int to) {
if(!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
if (this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE;
this.setNumberOfEdges(this.numberOfEdges() - 1);
return true;
}
}
return false;
}
/**
* this gives a list of vertices in the graph and their adjacencies
*
* @return returns a string describing this graph
*/
public String toString() {
String s = new String();
s = " ";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " ";
}
s = s + " \n";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " : ";
for (int j = 0; j < this.numberOfVertices(); j++) {
s = s + String.valueOf(this._adjacency[i][j]) + " ";
}
s = s + "\n";
}
return s;
}
}

View File

@ -1,114 +0,0 @@
// A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
//adjacency matrix representation of the graph
import java.lang.*;
class PrimMST
{
// Number of vertices in the graph
private static final int V=5;
// A utility function to find the vertex with minimum key
// value, from the set of vertices not yet included in MST
int minKey(int key[], Boolean mstSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index=-1;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
{
min = key[v];
min_index = v;
}
return min_index;
}
// A utility function to print the constructed MST stored in
// parent[]
void printMST(int parent[], int n, int graph[][])
{
System.out.println("Edge Weight");
for (int i = 1; i < V; i++)
System.out.println(parent[i]+" - "+ i+" "+
graph[i][parent[i]]);
}
// Function to construct and print MST for a graph represented
// using adjacency matrix representation
void primMST(int graph[][])
{
// Array to store constructed MST
int parent[] = new int[V];
// Key values used to pick minimum weight edge in cut
int key[] = new int [V];
// To represent set of vertices not yet included in MST
Boolean mstSet[] = new Boolean[V];
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++)
{
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
// Always include first 1st vertex in MST.
key[0] = 0; // Make key 0 so that this vertex is
// picked as first vertex
parent[0] = -1; // First node is always root of MST
// The MST will have V vertices
for (int count = 0; count < V-1; count++)
{
// Pick thd minimum key vertex from the set of vertices
// not yet included in MST
int u = minKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = true;
// Update key value and parent index of the adjacent
// vertices of the picked vertex. Consider only those
// vertices which are not yet included in MST
for (int v = 0; v < V; v++)
// graph[u][v] is non zero only for adjacent vertices of m
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v]!=0 && mstSet[v] == false &&
graph[u][v] < key[v])
{
parent[v] = u;
key[v] = graph[u][v];
}
}
// print the constructed MST
printMST(parent, V, graph);
}
public static void main (String[] args)
{
/* Let us create the following graph
2 3
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
PrimMST t = new PrimMST();
int graph[][] = new int[][] {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0},
};
// Print the solution
t.primMST(graph);
}
}

View File

@ -1,283 +0,0 @@
<<<<<<< HEAD:Data Structures/HashMap/HashMap.java
import java.util.ArrayList;
import java.util.LinkedList;
public class HashMap<K,V> {
public class hmnodes{ //HashMap nodes
K key;
V value;
}
private int size=0; //size of hashmap
private LinkedList<hmnodes> buckets[]; //array of addresses of list
public HashMap(){
buckets=new LinkedList[4]; //initially create bucket of any size
for(int i=0;i<4;i++)
buckets[i]=new LinkedList<>();
}
public void put(K key,V value) throws Exception{
int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index
int fountAt=find(bi,key); //check if key already exists or not
if(fountAt==-1){
hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert
temp.key=key;
temp.value=value;
buckets[bi].addLast(temp);
this.size++;
}else{
buckets[bi].get(fountAt).value=value;//if already exist modify the value
}
double lambda = (this.size*1.0)/this.buckets.length;
if(lambda>2.0){
rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0
}
return;
}
public V get(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return null;
}else{
return buckets[bi].get(fountAt).value;
}
}
public V remove(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return null;
}else{
this.size--;
return buckets[bi].remove(fountAt).value;
}
}
public boolean containskey(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return false;
}else{
return true;
}
}
public int size(){
return this.size;
}
public boolean isempty(){
return this.size==0;
}
public ArrayList<K> keyset() throws Exception{
ArrayList<K> arr=new ArrayList<>();
for(int i=0;i<buckets.length;i++){
for(int j=0;j<buckets[i].size();j++){
arr.add(buckets[i].get(j).key);
}
}
return arr;
}
public ArrayList<V> valueset() throws Exception{
ArrayList<V> arr=new ArrayList<>();
for(int i=0;i<buckets.length;i++){
for(int j=0;j<buckets[i].size();j++){
arr.add(buckets[i].get(j).value);
}
}
return arr;
}
public void display() throws Exception{
for(int i=0;i<buckets.length;i++){
System.out.print("Bucket: "+i+" ");
for(int j=0;j<buckets[i].size();j++){
hmnodes temp=buckets[i].get(j);
System.out.print("["+temp.key+"->"+temp.value+"]");
}
System.out.println();
}
}
public int find(int bi,K key) throws Exception{
for(int i=0;i<buckets[bi].size();i++){
if(key.equals(buckets[bi].get(i).key))
return i;
}
return -1;
}
public int bucketIndex(K key) throws Exception{
int bi=key.hashCode();
return Math.abs(bi%buckets.length);
}
private void rehash() throws Exception{
LinkedList<hmnodes> ob[]= buckets;
buckets=new LinkedList[ob.length*2];
for(int i=0;i<ob.length*2;i++)
buckets[i]=new LinkedList<>();
size = 0;
for(int i=0;i<ob.length;i++){
for(int j=0;j<ob[i].size();j++){
put(ob[i].get(j).key,ob[i].get(j).value);
}
}
}
}
=======
import java.util.ArrayList;
import java.util.LinkedList;
public class HashMap<K,V> {
public class hmnodes{ //HashMap nodes
K key;
V value;
}
private int size=0; //size of hashmap
private LinkedList<hmnodes> buckets[]; //array of addresses of list
public HashMap(){
buckets=new LinkedList[4]; //initially create bucket of any size
for(int i=0;i<4;i++)
buckets[i]=new LinkedList<>();
}
public void put(K key,V value) throws Exception{
int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index
int fountAt=find(bi,key); //check if key already exists or not
if(fountAt==-1){
hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert
temp.key=key;
temp.value=value;
buckets[bi].addLast(temp);
this.size++;
}else{
buckets[bi].get(fountAt).value=value;//if already exist modify the value
}
double lambda = (this.size*1.0)/this.buckets.length;
if(lambda>2.0){
rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0
}
return;
}
public V get(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return null;
}else{
return buckets[bi].get(fountAt).value;
}
}
public V remove(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return null;
}else{
this.size--;
return buckets[bi].remove(fountAt).value;
}
}
public boolean containskey(K key) throws Exception{
int bi=bucketIndex(key);
int fountAt=find(bi,key);
if(fountAt==-1){
return false;
}else{
return true;
}
}
public int size(){
return this.size;
}
public boolean isempty(){
return this.size==0;
}
public ArrayList<K> keyset() throws Exception{
ArrayList<K> arr=new ArrayList<>();
for(int i=0;i<buckets.length;i++){
for(int j=0;j<buckets[i].size();j++){
arr.add(buckets[i].get(j).key);
}
}
return arr;
}
public ArrayList<V> valueset() throws Exception{
ArrayList<V> arr=new ArrayList<>();
for(int i=0;i<buckets.length;i++){
for(int j=0;j<buckets[i].size();j++){
arr.add(buckets[i].get(j).value);
}
}
return arr;
}
public void display() throws Exception{
for(int i=0;i<buckets.length;i++){
System.out.print("Bucket: "+i+" ");
for(int j=0;j<buckets[i].size();j++){
hmnodes temp=buckets[i].get(j);
System.out.print("["+temp.key+"->"+temp.value+"]");
}
System.out.println();
}
}
public int find(int bi,K key) throws Exception{
for(int i=0;i<buckets[bi].size();i++){
if(key.equals(buckets[bi].get(i).key))
return i;
}
return -1;
}
public int bucketIndex(K key) throws Exception{
int bi=key.hashCode();
return Math.abs(bi%buckets.length);
}
private void rehash() throws Exception{
LinkedList<hmnodes> ob[]= buckets;
buckets=new LinkedList[ob.length*2];
for(int i=0;i<ob.length*2;i++)
buckets[i]=new LinkedList<>();
size = 0;
for(int i=0;i<ob.length;i++){
for(int j=0;j<ob[i].size();j++){
put(ob[i].get(j).key,ob[i].get(j).value);
}
}
}
}
>>>>>>> 7e3a8c55c865471a33f6932a022a1059c5243fc3:data_structures/HashMap/HashMap.java

View File

@ -1,18 +0,0 @@
/**
*
*/
package heaps;
/**
* @author Nicolas Renard
* Exception to be thrown if the getElement method is used on an empty heap.
*
*/
@SuppressWarnings("serial")
public class EmptyHeapException extends Exception {
public EmptyHeapException(String message) {
super(message);
}
}

View File

@ -1,41 +0,0 @@
package heaps;
/**
* Interface common to heap data structures.<br>
* <p>Heaps are tree-like data structures that allow storing elements in a specific
* way. Each node corresponds to an element and has one parent node (except for the root) and
* at most two children nodes. Every element contains a key, and those keys
* indicate how the tree shall be built. For instance, for a min-heap, the key of a node shall
* be greater than or equal to its parent's and lower than or equal to its children's (the opposite rule applies to a
* max-heap).</p>
* <p>All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in
* O(log n) time.</p>
* @author Nicolas Renard
*
*
*/
public interface Heap {
/**
*
* @return the top element in the heap, the one with lowest key for min-heap or with
* the highest key for max-heap
* @throws Exception if heap is empty
*/
public abstract HeapElement getElement() throws EmptyHeapException;
/**
* Inserts an element in the heap. Adds it to then end and toggle it until it finds its
* right position.
*
* @param element an instance of the HeapElement class.
*/
public abstract void insertElement(HeapElement element);
/**
* Delete an element in the heap.
*
* @param elementIndex int containing the position in the heap of the element to be deleted.
*/
public abstract void deleteElement(int elementIndex);
}

View File

@ -1,132 +0,0 @@
/**
*
*/
package heaps;
import java.lang.Double;
import java.lang.Object;
/**
* Class for heap elements.<br>
* <p>A heap element contains two attributes: a key which will be used to build the tree (int
* or double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit
* to carry any information he/she likes. Be aware that the use of a mutable object might
* jeopardize the integrity of this information. </p>
* @author Nicolas Renard
*
*/
public class HeapElement {
private final double key;
private final Object additionalInfo;
// Constructors
/**
*
* @param key : a number of primitive type 'double'
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
* additional information of use for the user
*/
public HeapElement(double key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
*
* @param key : a number of primitive type 'int'
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
* additional information of use for the user
*/
public HeapElement(int key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
*
* @param key : a number of object type 'Integer'
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
* additional information of use for the user
*/
public HeapElement(Integer key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
*
* @param key : a number of object type 'Double'
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
* additional information of use for the user
*/
public HeapElement(Double key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
*
* @param key : a number of primitive type 'double'
*/
public HeapElement(double key) {
this.key = key;
this.additionalInfo = null;
}
/**
*
* @param key : a number of primitive type 'int'
*/
public HeapElement(int key) {
this.key = key;
this.additionalInfo = null;
}
/**
*
* @param key : a number of object type 'Integer'
*/
public HeapElement(Integer key) {
this.key = key;
this.additionalInfo = null;
}
/**
*
* @param key : a number of object type 'Double'
*/
public HeapElement(Double key) {
this.key = key;
this.additionalInfo = null;
}
// Getters
/**
* @return the object containing the additional info provided by the user.
*/
public Object getInfo() {
return additionalInfo;
}
/**
* @return the key value of the element
*/
public double getKey() {
return key;
}
// Overridden object methods
public String toString() {
return "Key: " + key + " - " +additionalInfo.toString();
}
/**
*
* @param otherHeapElement
* @return true if the keys on both elements are identical and the additional info objects
* are identical.
*/
public boolean equals(HeapElement otherHeapElement) {
return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo));
}
}

View File

@ -1,115 +0,0 @@
package heaps;
import java.util.ArrayList;
import java.util.List;
/**
* Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
* to its children's.
* @author Nicolas Renard
*
*/
public class MaxHeap implements Heap {
private final List<HeapElement> maxHeap;
public MaxHeap(List<HeapElement> listElements) throws Exception {
maxHeap = new ArrayList<HeapElement>();
for (HeapElement heapElement : listElements) {
if (heapElement != null) insertElement(heapElement);
else System.out.println("Null element. Not added to heap");
}
if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap.");
}
// Get the element at a given index. The key for the list is equal to index value - 1
public HeapElement getElement(int elementIndex) {
if ((elementIndex <= 0) && (elementIndex > maxHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
return maxHeap.get(elementIndex - 1);
}
// Get the key of the element at a given index
private double getElementKey(int elementIndex) {
return maxHeap.get(elementIndex - 1).getKey();
}
// Swaps two elements in the heap
private void swap(int index1, int index2) {
HeapElement temporaryElement = maxHeap.get(index1 - 1);
maxHeap.set(index1 - 1, maxHeap.get(index2 - 1));
maxHeap.set(index2 - 1, temporaryElement);
}
// Toggle an element up to its right place as long as its key is lower than its parent's
private void toggleUp(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
while (getElementKey((int) Math.floor(elementIndex/2)) < key) {
swap(elementIndex, (int) Math.floor(elementIndex/2));
elementIndex = (int) Math.floor(elementIndex/2);
}
}
// Toggle an element down to its right place as long as its key is higher
// than any of its children's
private void toggleDown(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
boolean wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
while ((2*elementIndex <= maxHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any.
if ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex*2 + 1) > getElementKey(elementIndex*2))) {
swap(elementIndex, 2*elementIndex + 1);
elementIndex = 2*elementIndex + 1;
}
else {
swap(elementIndex, 2*elementIndex);
elementIndex = 2*elementIndex;
}
wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size())));
}
}
private HeapElement extractMax() {
HeapElement result = maxHeap.get(0);
deleteElement(0);
return result;
}
@Override
public void insertElement(HeapElement element) {
maxHeap.add(element);
toggleUp(maxHeap.size());
}
@Override
public void deleteElement(int elementIndex) {
if (maxHeap.isEmpty())
try {
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) {
e.printStackTrace();
}
if ((elementIndex > maxHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
// The last element in heap replaces the one to be deleted
maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
maxHeap.remove(maxHeap.size());
// Shall the new element be moved up...
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
// ... or down ?
else if (((2*elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2))) ||
((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2)))) toggleDown(elementIndex);
}
@Override
public HeapElement getElement() throws EmptyHeapException {
try {
return extractMax();
} catch (Exception e) {
throw new EmptyHeapException("Heap is empty. Error retrieving element");
}
}
}

View File

@ -1,115 +0,0 @@
/**
*
*/
package heaps;
import java.util.ArrayList;
import java.util.List;
/**
* Heap tree where a node's key is higher than or equal to its parent's and lower than or equal
* to its children's.
* @author Nicolas Renard
*
*/
public class MinHeap implements Heap {
private final List<HeapElement> minHeap;
public MinHeap(List<HeapElement> listElements) throws Exception {
minHeap = new ArrayList<HeapElement>();
for (HeapElement heapElement : listElements) {
if (heapElement != null) insertElement(heapElement);
else System.out.println("Null element. Not added to heap");
}
if (minHeap.size() == 0) System.out.println("No element has been added, empty heap.");
}
// Get the element at a given index. The key for the list is equal to index value - 1
public HeapElement getElement(int elementIndex) {
if ((elementIndex <= 0) && (elementIndex > minHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range");
return minHeap.get(elementIndex - 1);
}
// Get the key of the element at a given index
private double getElementKey(int elementIndex) {
return minHeap.get(elementIndex - 1).getKey();
}
// Swaps two elements in the heap
private void swap(int index1, int index2) {
HeapElement temporaryElement = minHeap.get(index1 - 1);
minHeap.set(index1 - 1, minHeap.get(index2 - 1));
minHeap.set(index2 - 1, temporaryElement);
}
// Toggle an element up to its right place as long as its key is lower than its parent's
private void toggleUp(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey();
while (getElementKey((int) Math.floor(elementIndex/2)) > key) {
swap(elementIndex, (int) Math.floor(elementIndex/2));
elementIndex = (int) Math.floor(elementIndex/2);
}
}
// Toggle an element down to its right place as long as its key is higher
// than any of its children's
private void toggleDown(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey();
boolean wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
while ((2*elementIndex <= minHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any.
if ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex*2 + 1) < getElementKey(elementIndex*2))) {
swap(elementIndex, 2*elementIndex + 1);
elementIndex = 2*elementIndex + 1;
}
else {
swap(elementIndex, 2*elementIndex);
elementIndex = 2*elementIndex;
}
wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size())));
}
}
private HeapElement extractMin() {
HeapElement result = minHeap.get(0);
deleteElement(0);
return result;
}
@Override
public void insertElement(HeapElement element) {
minHeap.add(element);
toggleUp(minHeap.size());
}
@Override
public void deleteElement(int elementIndex) {
if (minHeap.isEmpty())
try {
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) {
e.printStackTrace();
}
if ((elementIndex > minHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range");
// The last element in heap replaces the one to be deleted
minHeap.set(elementIndex - 1, getElement(minHeap.size()));
minHeap.remove(minHeap.size());
// Shall the new element be moved up...
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex);
// ... or down ?
else if (((2*elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2))) ||
((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2)))) toggleDown(elementIndex);
}
@Override
public HeapElement getElement() throws EmptyHeapException {
try {
return extractMin();
} catch (Exception e) {
throw new EmptyHeapException("Heap is empty. Error retrieving element");
}
}
}

View File

@ -1,54 +0,0 @@
public class CircleLinkedList<E>{
private static class Node<E>{
Node<E> next;
E value;
private Node(E value, Node<E> next){
this.value = value;
this.next = next;
}
}
//For better O.O design this should be private allows for better black box design
private int size;
//this will point to dummy node;
private Node<E> head;
//constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty;
public CircleLinkedList(){
//creation of the dummy node
head = new Node<E>(null,head);
size = 0;
}
// getter for the size... needed because size is private.
public int getSize(){ return size;}
// for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really.
public void append(E value){
if(value == null){
// we do not want to add null elements to the list.
throw new NullPointerException("Cannot add null element to the list");
}
//head.next points to the last element;
head.next = new Node<E>(value,head);
size++;}
public E remove(int pos){
if(pos>size || pos< 0){
//catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
Node<E> iterator = head.next;
//we need to keep track of the element before the element we want to remove we can see why bellow.
Node<E> before = head;
for(int i = 1; i<=pos; i++){
iterator = iterator.next;
before = before.next;
}
E saved = iterator.value;
// assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
before.next = iterator.next;
// scrubbing
iterator.next = null;
iterator.value = null;
return saved;
}
}

View File

@ -1,214 +0,0 @@
/**
* This class implements a DoublyLinkedList. This is done using the classes
* LinkedList and Link.
*
* A linked list is simplar to an array, it holds values. However,
* links in a linked list do not have indees. With a linked list
* you do not need to predetermine it's size as it grows and shrinks
* as it is edited. This is an example of a double ended, doubly
* linked list. Each link references the next link and the previous
* one.
*
* @author Unknown
*
*/
class DoublyLinkedList{
/** Head refers to the front of the list */
private Link head;
/** Tail refers to the back of the list */
private Link tail;
/**
* Constructor
*/
public DoublyLinkedList(){
head = null;
tail = null;
}
/**
* Insert an element at the head
*
* @param x Element to be inserted
*/
public void insertHead(int x){
Link newLink = new Link(x); //Create a new link with a value attached to it
if(isEmpty()) //Set the first element added to be the tail
tail = newLink;
else
head.previous = newLink; // newLink <-- currenthead(head)
newLink.next = head; // newLink <--> currenthead(head)
head = newLink; // newLink(head) <--> oldhead
}
/**
* Insert an element at the tail
*
* @param x Element to be inserted
*/
public void insertTail(int x){
Link newLink = new Link(x);
newLink.next = null; // currentTail(tail) newlink -->
tail.next = newLink; // currentTail(tail) --> newLink -->
newLink.previous = tail; // currentTail(tail) <--> newLink -->
tail = newLink; // oldTail <--> newLink(tail) -->
}
/**
* Delete the element at the head
*
* @return The new head
*/
public Link deleteHead(){
Link temp = head;
head = head.next; // oldHead <--> 2ndElement(head)
head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
if(head == null)
tail = null;
return temp;
}
/**
* Delete the element at the tail
*
* @return The new tail
*/
public Link deleteTail(){
Link temp = tail;
tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
tail.next = null; // 2ndLast(tail) --> null
return temp;
}
/**
* Delete the element from somewhere in the list
*
* @param x element to be deleted
* @return Link deleted
*/
public Link delete(int x){
Link current = head;
while(current.value != x) //Find the position to delete
current = current.next;
if(current == head)
deleteHead();
else if(current == tail)
deleteTail();
else{ //Before: 1 <--> 2(current) <--> 3
current.previous.next = current.next; // 1 --> 3
current.next.previous = current.previous; // 1 <--> 3
}
return current;
}
/**
* Inserts element and reorders
*
* @param x Element to be added
*/
public void insertOrdered(int x){
Link newLink = new Link(x);
Link current = head;
while(current != null && x > current.value) //Find the position to insert
current = current.next;
if(current == head)
insertHead(x);
else if(current == null)
insertTail(x);
else{ //Before: 1 <--> 2(current) <--> 3
newLink.previous = current.previous; // 1 <-- newLink
current.previous.next = newLink; // 1 <--> newLink
newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3
current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3
}
}
/**
* Returns true if list is empty
*
* @return true if list is empty
*/
public boolean isEmpty(){
return(head == null);
}
/**
* Prints contents of the list
*/
public void display(){ //Prints contents of the list
Link current = head;
while(current!=null){
current.displayLink();
current = current.next;
}
System.out.println();
}
}
/**
* This class is used to implement the nodes of the
* linked list.
*
* @author Unknown
*
*/
class Link{
/** Value of node */
public int value;
/** This points to the link in front of the new link */
public Link next;
/** This points to the link behind the new link */
public Link previous;
/**
* Constructor
*
* @param value Value of node
*/
public Link(int value){
this.value = value;
}
/**
* Displays the node
*/
public void displayLink(){
System.out.print(value+" ");
}
/**
* Main Method
*
* @param args Command line arguments
*/
public static void main(String args[]){
DoublyLinkedList myList = new DoublyLinkedList();
myList.insertHead(13);
myList.insertHead(7);
myList.insertHead(10);
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
myList.insertTail(11);
myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
myList.deleteTail();
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
myList.delete(7);
myList.display(); // <-- 10(head) <--> 13(tail) -->
myList.insertOrdered(23);
myList.insertOrdered(67);
myList.insertOrdered(3);
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
}
}

View File

@ -1,151 +0,0 @@
/**
* This class implements a SinglyLinked List. This is done
* using SinglyLinkedList class and a LinkForLinkedList Class.
*
* A linked list is implar to an array, it hold values.
* However, links in a linked list do not have indexes. With
* a linked list you do not need to predetermine it's size as
* it gorws and shrinks as it is edited. This is an example of
* a singly linked list. Elements can only be added/removed
* at the head/front of the list.
*
* @author Unknown
*
*/
class SinglyLinkedList{
/**Head refered to the front of the list */
private Node head;
/**
* Constructor of SinglyLinkedList
*/
public SinglyLinkedList(){
head = null;
}
/**
* This method inserts an element at the head
*
* @param x Element to be added
*/
public void insertHead(int x){
Node newNode = new Node(x); //Create a new link with a value attached to it
newNode.next = head; //Set the new link to point to the current head
head = newNode; //Now set the new link to be the head
}
/**
* Inserts a new node at a specified position
* @param head head node of the linked list
* @param data data to be stored in a new node
* @param position position at which a new node is to be inserted
* @return reference of the head of the linked list
*/
Node InsertNth(Node head, int data, int position) {
Node newNode = new Node();
newNode.data = data;
if (position == 0) {
newNode.next = head;
return newNode;
}
Node current = head;
while (--position > 0) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
return head;
}
/**
* This method deletes an element at the head
*
* @return The element deleted
*/
public Node deleteHead(){
Node temp = head;
head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head
return temp;
}
/**
* Checks if the list is empty
*
* @return true is list is empty
*/
public boolean isEmpty(){
return(head == null);
}
/**
* Prints contents of the list
*/
public void display(){
Node current = head;
while(current!=null){
System.out.print(current.getValue()+" ");
current = current.next;
}
System.out.println();
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
SinglyLinkedList myList = new SinglyLinkedList();
System.out.println(myList.isEmpty()); //Will print true
myList.insertHead(5);
myList.insertHead(7);
myList.insertHead(10);
myList.display(); // 10(head) --> 7 --> 5
myList.deleteHead();
myList.display(); // 7(head) --> 5
}
}
/**
* This class is the nodes of the SinglyLinked List.
* They consist of a vlue and a pointer to the node
* after them.
*
* @author Unknown
*
*/
class Node{
/** The value of the node */
public int value;
/** Point to the next node */
public Node next; //This is what the link will point to
/**
* Constructor
*
* @param valuein Value to be put in the node
*/
public Node(int valuein){
value = valuein;
}
/**
* Returns value of the node
*/
public int getValue(){
return value;
}
}

View File

@ -1,259 +0,0 @@
/**
* Matrix data-type.
*
* @author Kyler Smith, 2017
*/
public class Matrix {
public static void main(String[] args) {
int[][] data1 = new int[0][0];
int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] data3 = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
Matrix m1 = new Matrix(data1);
Matrix m2 = new Matrix(data2);
Matrix m3 = new Matrix(data3);
System.out.println("m1 --> Rows: " + m1.getRows() + " Columns: " + m1.getColumns());
System.out.println("m2 --> Rows: " + m2.getRows() + " Columns: " + m2.getColumns());
System.out.println("m3 --> Rows: " + m3.getRows() + " Columns: " + m3.getColumns());
//check for reference issues
System.out.println("m2 -->\n" + m2);
data2[1][1] = 101;
System.out.println("m2 -->\n" + m2);
//test equals
System.out.println("m2==null: " + m2.equals(null)); //false
System.out.println("m3==\"MATRIX\": " + m2.equals("MATRIX")); //false
System.out.println("m2==m1: " + m2.equals(m1)); //false
System.out.println("m2==m2: " + m2.equals(m2)); //true
System.out.println("m2==m3: " + m2.equals(m3)); //false
//test operations (valid)
System.out.println("2 * m2:\n" + m2.scale(2));
System.out.println("m2 / 2:\n" + m2.divide(2));
System.out.println("m2 + m3:\n" + m2.plus(m3));
System.out.println("m2 - m3:\n" + m2.minus(m3));
System.out.println("m2 * m3: \n"+m2.multiply(m3));
}
/**
* Data needs to be a deep copy as not to change the original state.
*/
private int[][] data;
/**
* Constructor for the matrix takes in a 2D array
*
* @param pData
*/
public Matrix(int[][] pData) {
/** Make a deep copy of the data */
if(pData.length != 0) {
int[][] newData = new int[pData.length][pData[0].length];
for(int i = 0; i < pData.length; i++)
for(int j = 0; j < pData[0].length; j++)
newData[i][j] = pData[i][j];
this.data = newData;
} else {
this.data = null;
}
}
/**
* Returns the element specified by the given location
*
* @param x : x cooridinate
* @param y : y cooridinate
* @return int : value at location
*/
public int getElement(int x, int y) {
return data[x][y];
}
/**
* Returns the number of rows in the Matrix
*
* @return rows
*/
public int getRows() {
if(this.data == null)
return 0;
return data.length;
}
/**
* Returns the number of rows in the Matrix
*
* @return columns
*/
public int getColumns() {
if(this.data == null)
return 0;
return data[0].length;
}
/**
* Returns this matrix scaled by a factor. That is, computes sA where s is a
* constant and A is a matrix (this object).
*
* @param scalar : value to scale by
* @return A new matrix scaled by the scalar value
*/
public Matrix scale(int scalar) {
int[][] newData = new int[this.data.length][this.data[0].length];
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] * scalar;
return new Matrix(newData);
}
/**
* Returns this matrix divided by a factor. That is, computes sA where s is a
* constant and A is a matrix (this object).
*
* @param scalar : value to divide by
* @return A new matrix scaled by the scalar value
*/
public Matrix divide(int scalar) {
int[][] newData = new int[this.data.length][this.data[0].length];
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] / scalar;
return new Matrix(newData);
}
/**
* Adds this matrix to another matrix.
*
* @param other : Matrix to be added
* @return addend
*/
public Matrix plus(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][this.data[0].length];
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
throw new RuntimeException("Not the same size matrix.");
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] + other.getElement(i, j);
return new Matrix(newData);
}
/**
* Subtracts this matrix from another matrix.
*
* @param other : Matrix to be subtracted
* @return difference
*/
public Matrix minus(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][this.data[0].length];
if(this.getRows() != other.getRows() || this.getColumns() != other.getColumns())
throw new RuntimeException("Not the same size matrix.");
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < this.getColumns(); ++j)
newData[i][j] = this.data[i][j] - other.getElement(i, j);
return new Matrix(newData);
}
/**
* Multiplies this matrix with another matrix.
*
* @param other : Matrix to be multiplied with
* @return product
*/
public Matrix multiply(Matrix other) throws RuntimeException {
int[][] newData = new int[this.data.length][other.getColumns()];
if(this.getColumns() !=other.getRows())
throw new RuntimeException("The two matrices cannot be multiplied.");
int sum;
for (int i = 0; i < this.getRows(); ++i)
for(int j = 0; j < other.getColumns(); ++j){
sum = 0;
for(int k=0;k<this.getColumns();++k){
sum += this.data[i][k] * other.getElement(k, j);
}
newData[i][j] = sum;
}
return new Matrix(newData);
}
/**
* Checks if the matrix passed is equal to this matrix
*
* @param other : the other matrix
* @return boolean
*/
public boolean equals(Matrix other) {
return this == other;
}
/**
* Returns the Matrix as a String in the following format
*
* [ a b c ] ...
* [ x y z ] ...
* [ i j k ] ...
* ...
*
* @return Matrix as String
* TODO: Work formatting for different digit sizes
*/
public String toString() {
String str = "";
for(int i = 0; i < this.data.length; i++) {
str += "[ ";
for(int j = 0; j < this.data[0].length; j++) {
str += data[i][j];
str += " ";
}
str += "]";
str += "\n";
}
return str;
}
/**
* Returns transposed matrix of this matrix.
*
* @return transposed Matrix.
*/
public Matrix transpose() {
int[][] newData = new int[this.data[0].length][this.data.length];
for (int i = 0; i < this.getColumns(); ++i)
for(int j = 0; j < this.getRows(); ++j)
newData[i][j] = this.data[j][i];
return new Matrix(newData);
}
}

View File

@ -1,42 +0,0 @@
import java.util.ArrayList;
public class GenericArrayListQueue<T> {
ArrayList<T> _queue = new ArrayList<T>();
private boolean hasElements() {
return !_queue.isEmpty();
}
public T peek() {
T result = null;
if(this.hasElements()) { result = _queue.get(0); }
return result;
}
public boolean add(T element) {
return _queue.add(element);
}
public T poll() {
T result = null;
if(this.hasElements()) { result = _queue.remove(0); }
return result;
}
public static void main(String[] args) {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<Integer>();
System.out.println("Running...");
assert queue.peek() == null;
assert queue.poll() == null;
assert queue.add(1) == true;
assert queue.peek() == 1;
assert queue.add(2) == true;
assert queue.peek() == 1;
assert queue.poll() == 1;
assert queue.peek() == 2;
assert queue.poll() == 2;
assert queue.peek() == null;
assert queue.poll() == null;
System.out.println("Finished.");
}
}

View File

@ -1,123 +0,0 @@
/**
* This class implements a PriorityQueue.
*
* A priority queue adds elements into positions based on their priority.
* So the most important elements are placed at the front/on the top.
* In this example I give numbers that are bigger, a higher priority.
* Queues in theory have no fixed size but when using an array
* implementation it does.
*
* @author Unknown
*
*/
class PriorityQueue{
/** The max size of the queue */
private int maxSize;
/** The array for the queue */
private int[] queueArray;
/** How many items are in the queue */
private int nItems;
/**
* Constructor
*
* @param size Size of the queue
*/
public PriorityQueue(int size){
maxSize = size;
queueArray = new int[size];
nItems = 0;
}
/**
* Inserts an element in it's appropriate place
*
* @param value Value to be inserted
*/
public void insert(int value){
if(nItems == 0){
queueArray[0] = value;
}
else{
int j = nItems;
while(j > 0 && queueArray[j-1] > value){
queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion
j--;
}
queueArray[j] = value; //Once the correct position is found the value is inserted
}
nItems++;
}
/**
* Remove the element from the front of the queue
*
* @return The element removed
*/
public int remove(){
return queueArray[--nItems];
}
/**
* Checks what's at the front of the queue
*
* @return element at the front of the queue
*/
public int peek(){
return queueArray[nItems-1];
}
/**
* Returns true if the queue is empty
*
* @return true if the queue is empty
*/
public boolean isEmpty(){
return(nItems == 0);
}
/**
* Returns true if the queue is full
*
* @return true if the queue is full
*/
public boolean isFull(){
return(nItems == maxSize);
}
/**
* Returns the number of elements in the queue
*
* @return number of elements in the queue
*/
public int getSize(){
return nItems;
}
}
/**
* This class implements the PriorityQueue class above.
*
* @author Unknown
*
*/
public class PriorityQueues{
/**
* Main method
*
* @param args Command Line Arguments
*/
public static void main(String args[]){
PriorityQueue myQueue = new PriorityQueue(4);
myQueue.insert(10);
myQueue.insert(2);
myQueue.insert(5);
myQueue.insert(3);
//[2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
for(int i = 3; i>=0; i--)
System.out.print(myQueue.remove() + " "); //will print the queue in reverse order [10, 5, 3, 2]
//As you can see, a Priority Queue can be used as a sorting algotithm
}
}

View File

@ -1,148 +0,0 @@
/**
* This implements Queues by using the class Queue.
*
* A queue data structure functions the same as a real world queue.
* The elements that are added first are the first to be removed.
* New elements are added to the back/rear of the queue.
*
* @author Unknown
*
*/
class Queue{
/** Max size of the queue */
private int maxSize;
/** The array representing the queue */
private int[] queueArray;
/** Front of the queue */
private int front;
/** Rear of the queue */
private int rear;
/** How many items are in the queue */
private int nItems;
/**
* Constructor
*
* @param size Size of the new queue
*/
public Queue(int size){
maxSize = size;
queueArray = new int[size];
front = 0;
rear = -1;
nItems = 0;
}
/**
* Inserts an element at the rear of the queue
*
* @param x element to be added
* @return True if the element was added successfully
*/
public boolean insert(int x){
if(isFull())
return false;
if(rear == maxSize-1) //If the back of the queue is the end of the array wrap around to the front
rear = -1;
rear++;
queueArray[rear] = x;
nItems++;
return true;
}
/**
* Remove an element from the front of the queue
*
* @return the new front of the queue
*/
public int remove(){ //Remove an element from the front of the queue
if(isEmpty()){
System.out.println("Queue is empty");
return -1;
}
int temp = queueArray[front];
front++;
if(front == maxSize) //Dealing with wrap-around again
front = 0;
nItems--;
return temp;
}
/**
* Checks what's at the front of the queue
*
* @return element at the front of the queue
*/
public int peekFront(){
return queueArray[front];
}
/**
* Checks what's at the rear of the queue
*
* @return element at the rear of the queue
*/
public int peekRear(){
return queueArray[rear];
}
/**
* Returns true if the queue is empty
*
* @return true if the queue is empty
*/
public boolean isEmpty(){
return(nItems == 0);
}
/**
* Returns true if the queue is full
*
* @return true if the queue is full
*/
public boolean isFull(){
return(nItems == maxSize);
}
/**
* Returns the number of elements in the queue
*
* @return number of elements in the queue
*/
public int getSize(){
return nItems;
}
}
/**
* This class is the example for the Queue class
*
* @author Unknown
*
*/
public class Queues{
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
Queue myQueue = new Queue(4);
myQueue.insert(10);
myQueue.insert(2);
myQueue.insert(5);
myQueue.insert(3);
//[10(front), 2, 5, 3(rear)]
System.out.println(myQueue.isFull()); //Will print true
myQueue.remove(); //Will make 2 the new front, making 10 no longer part of the queue
//[10, 2(front), 5, 3(rear)]
myQueue.insert(7); //Insert 7 at the rear which will be index 0 because of wrap around
// [7(rear), 2(front), 5, 3]
System.out.println(myQueue.peekFront()); //Will print 2
System.out.println(myQueue.peekRear()); //Will print 7
}
}

View File

@ -1,183 +0,0 @@
/**
* Implementation of a stack using nodes.
* Unlimited size, no arraylist.
*
* @author Kyler Smith, 2017
*/
public class NodeStack<Item> {
/**
* Entry point for the program.
*/
public static void main(String[] args) {
NodeStack<Integer> Stack = new NodeStack<Integer>();
Stack.push(3);
Stack.push(4);
Stack.push(5);
System.out.println("Testing :");
Stack.print(); // prints : 5 4 3
Integer x = Stack.pop(); // x = 5
Stack.push(1);
Stack.push(8);
Integer y = Stack.peek(); // y = 8
System.out.println("Testing :");
Stack.print(); // prints : 8 1 4 3
System.out.println("Testing :");
System.out.println("x : " + x);
System.out.println("y : " + y);
}
/**
* Information each node should contain.
* @value data : information of the value in the node
* @value head : the head of the stack
* @value next : the next value from this node
* @value previous : the last value from this node
* @value size : size of the stack
*/
private Item data;
private static NodeStack<?> head;
private NodeStack<?> next;
private NodeStack<?> previous;
private static int size = 0;
/**
* Constructors for the NodeStack.
*/
public NodeStack() {
}
private NodeStack(Item item) {
this.data = item;
}
/**
* Put a value onto the stack.
*
* @param item : value to be put on the stack.
*/
public void push(Item item) {
NodeStack<Item> newNs = new NodeStack<Item>(item);
if(this.isEmpty()) {
NodeStack.setHead(new NodeStack<>(item));
newNs.setNext(null);
newNs.setPrevious(null);
} else {
newNs.setPrevious(NodeStack.head);
NodeStack.head.setNext(newNs);
NodeStack.head = newNs;
}
NodeStack.setSize(NodeStack.getSize() + 1);
}
/**
* Value to be taken off the stack.
*
* @return item : value that is returned.
*/
public Item pop() {
Item item = (Item) NodeStack.head.getData();
NodeStack.head = NodeStack.head.getPrevious();
NodeStack.head.setNext(null);
NodeStack.setSize(NodeStack.getSize() - 1);
return item;
}
/**
* Value that is next to be taken off the stack.
*
* @return item : the next value that would be popped off the stack.
*/
public Item peek() {
return (Item) NodeStack.head.getData();
}
/**
* If the stack is empty or there is a value in.
*
* @return boolean : whether or not the stack has anything in it.
*/
public boolean isEmpty() {
return NodeStack.getSize() == 0;
}
/**
* Returns the size of the stack.
*
* @return int : number of values in the stack.
*/
public int size() {
return NodeStack.getSize();
}
/**
* Print the contents of the stack in the following format.
*
* x <- head (next out)
* y
* z <- tail (first in)
* .
* .
* .
*
*/
public void print() {
for(NodeStack<?> n = NodeStack.head; n != null; n = n.previous) {
System.out.println(n.getData().toString());
}
}
/** Getters and setters (private) */
private NodeStack<?> getHead() {
return NodeStack.head;
}
private static void setHead(NodeStack<?> ns) {
NodeStack.head = ns;
}
private NodeStack<?> getNext() {
return next;
}
private void setNext(NodeStack<?> next) {
this.next = next;
}
private NodeStack<?> getPrevious() {
return previous;
}
private void setPrevious(NodeStack<?> previous) {
this.previous = previous;
}
private static int getSize() {
return size;
}
private static void setSize(int size) {
NodeStack.size = size;
}
private Item getData() {
return this.data;
}
private void setData(Item item) {
this.data = item;
}
}

View File

@ -1,109 +0,0 @@
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
// An implementation of a Stack using a Linked List
class StackOfLinkedList {
public static void main(String[] args) {
LinkedListStack stack = new LinkedListStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.printStack();
System.out.println("Size of stack currently is: " + stack.getSize());
stack.pop();
stack.pop();
System.out.println("Top element of stack currently is: " + stack.peek());
}
}
// A node class
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
/**
* A class which implements a stack using a linked list
*
* Contains all the stack methods : push, pop, printStack, isEmpty
**/
class LinkedListStack {
Node head = null;
int size = 0;
public void push(int x) {
Node n = new Node(x);
if (getSize() == 0) {
head = n;
}
else {
Node temp = head;
n.next = temp;
head = n;
}
size++;
}
public void pop() {
if (getSize() == 0) {
System.out.println("Empty stack. Nothing to pop");
}
Node temp = head;
head = head.next;
size--;
System.out.println("Popped element is: " + temp.data);
}
public int peek() {
if (getSize() == 0) {
return -1;
}
return head.data;
}
public void printStack() {
Node temp = head;
System.out.println("Stack is printed as below: ");
while (temp != null) {
System.out.println(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public boolean isEmpty() {
return getSize() == 0;
}
public int getSize() {
return size;
}
}

View File

@ -1,240 +0,0 @@
import java.util.ArrayList;
/**
* This class implements a Stack using two different implementations.
* Stack is used with a regular array and Stack2 uses an ArrayList.
*
* A stack is exactly what it sounds like. An element gets added to the top of
* the stack and only the element on the top may be removed. This is an example
* of an array implementation of a Stack. So an element can only be added/removed
* from the end of the array. In theory stack have no fixed size, but with an
* array implementation it does.
*
* @author Unknown
*
*/
class Stack{
/** The max size of the Stack */
private int maxSize;
/** The array representation of the Stack */
private int[] stackArray;
/** The top of the stack */
private int top;
/**
* Constructor
*
* @param size Size of the Stack
*/
public Stack(int size){
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
/**
* Adds an element to the top of the stack
*
* @param value The element added
*/
public void push(int value){
if(!isFull()){ //Checks for a full stack
top++;
stackArray[top] = value;
}else{
resize(maxSize*2);
push(value);// don't forget push after resizing
}
}
/**
* Removes the top element of the stack and returns the value you've removed
*
* @return value popped off the Stack
*/
public int pop(){
if(!isEmpty()){ //Checks for an empty stack
return stackArray[top--];
}
if(top < maxSize/4){
resize(maxSize/2);
return pop();// don't forget pop after resizing
}
else{
System.out.println("The stack is already empty");
return -1;
}
}
/**
* Returns the element at the top of the stack
*
* @return element at the top of the stack
*/
public int peek(){
if(!isEmpty()){ //Checks for an empty stack
return stackArray[top];
}else{
System.out.println("The stack is empty, cant peek");
return -1;
}
}
private void resize(int newSize){
//private int[] transferArray = new int[newSize]; we can't put modifires here !
int[] transferArray = new int[newSize];
//for(int i = 0; i < stackArray.length(); i++){ the length isn't a method .
for(int i = 0; i < stackArray.length; i++){
transferArray[i] = stackArray[i];
stackArray = transferArray;
}
maxSize = newSize;
}
/**
* Returns true if the stack is empty
*
* @return true if the stack is empty
*/
public boolean isEmpty(){
return(top == -1);
}
/**
* Returns true if the stack is full
*
* @return true if the stack is full
*/
public boolean isFull(){
return(top+1 == maxSize);
}
/**
* Deletes everything in the Stack
*
* Doesn't delete elements in the array
* but if you call push method after calling
* makeEmpty it will overwrite previous
* values
*/
public void makeEmpty(){ //Doesn't delete elements in the array but if you call
top = -1; //push method after calling makeEmpty it will overwrite previous values
}
}
/**
* This is an ArrayList Implementation of stack, Where size is not
* a problem we can extend the stack as much as we want.
*
* @author Unknown
*
*/
class Stack2{
/** ArrayList representation of the stack */
ArrayList<Integer> stackList;
/**
* Constructor
*/
Stack2(){
stackList=new ArrayList<>();
}
/**
* Adds value to the end of list which
* is the top for stack
*
* @param value value to be added
*/
void push(int value){
stackList.add(value);
}
/**
* Pops last element of list which is indeed
* the top for Stack
*
* @return Element popped
*/
int pop(){
if(!isEmpty()){ // checks for an empty Stack
int popValue=stackList.get(stackList.size()-1);
stackList.remove(stackList.size()-1); //removes the poped element from the list
return popValue;
}
else{
System.out.print("The stack is already empty ");
return -1;
}
}
/**
* Checks for empty Stack
*
* @return true if stack is empty
*/
boolean isEmpty(){
if(stackList.isEmpty())
return true;
else return false;
}
/**
* Top element of stack
*
* @return top element of stack
*/
int peek(){
return stackList.get(stackList.size()-1);
}
}
/**
* This class implements the Stack and Stack2 created above
*
* @author Unknown
*
*/
public class Stacks{
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String args[]){
Stack myStack = new Stack(4); //Declare a stack of maximum size 4
//Populate the stack
myStack.push(5);
myStack.push(8);
myStack.push(2);
myStack.push(9);
System.out.println("*********************Stack Array Implementation*********************");
System.out.println(myStack.isEmpty()); //will print false
System.out.println(myStack.isFull()); //will print true
System.out.println(myStack.peek()); //will print 9
System.out.println(myStack.pop()); //will print 9
System.out.println(myStack.peek()); // will print 2
Stack2 myStack2 = new Stack2(); //Declare a stack of maximum size 4
//Populate the stack
myStack2.push(5);
myStack2.push(8);
myStack2.push(2);
myStack2.push(9);
System.out.println("*********************Stack List Implementation*********************");
System.out.println(myStack2.isEmpty()); //will print false
System.out.println(myStack2.peek()); //will print 9
System.out.println(myStack2.pop()); //will print 9
System.out.println(myStack2.peek()); // will print 2
System.out.println(myStack2.pop()); //will print 2
}
}

View File

@ -1,212 +0,0 @@
public class AVLTree {
private Node root;
private class Node {
private int key;
private int balance;
private int height;
private Node left, right, parent;
Node(int k, Node p) {
key = k;
parent = p;
}
}
public boolean insert(int key) {
if (root == null)
root = new Node(key, null);
else {
Node n = root;
Node parent;
while (true) {
if (n.key == key)
return false;
parent = n;
boolean goLeft = n.key > key;
n = goLeft ? n.left : n.right;
if (n == null) {
if (goLeft) {
parent.left = new Node(key, parent);
} else {
parent.right = new Node(key, parent);
}
rebalance(parent);
break;
}
}
}
return true;
}
private void delete(Node node){
if(node.left == null && node.right == null){
if(node.parent == null) root = null;
else{
Node parent = node.parent;
if(parent.left == node){
parent.left = null;
}else parent.right = null;
rebalance(parent);
}
return;
}
if(node.left!=null){
Node child = node.left;
while (child.right!=null) child = child.right;
node.key = child.key;
delete(child);
}else{
Node child = node.right;
while (child.left!=null) child = child.left;
node.key = child.key;
delete(child);
}
}
public void delete(int delKey) {
if (root == null)
return;
Node node = root;
Node child = root;
while (child != null) {
node = child;
child = delKey >= node.key ? node.right : node.left;
if (delKey == node.key) {
delete(node);
return;
}
}
}
private void rebalance(Node n) {
setBalance(n);
if (n.balance == -2) {
if (height(n.left.left) >= height(n.left.right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
} else if (n.balance == 2) {
if (height(n.right.right) >= height(n.right.left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n.parent != null) {
rebalance(n.parent);
} else {
root = n;
}
}
private Node rotateLeft(Node a) {
Node b = a.right;
b.parent = a.parent;
a.right = b.left;
if (a.right != null)
a.right.parent = a;
b.left = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateRight(Node a) {
Node b = a.left;
b.parent = a.parent;
a.left = b.right;
if (a.left != null)
a.left.parent = a;
b.right = a;
a.parent = b;
if (b.parent != null) {
if (b.parent.right == a) {
b.parent.right = b;
} else {
b.parent.left = b;
}
}
setBalance(a, b);
return b;
}
private Node rotateLeftThenRight(Node n) {
n.left = rotateLeft(n.left);
return rotateRight(n);
}
private Node rotateRightThenLeft(Node n) {
n.right = rotateRight(n.right);
return rotateLeft(n);
}
private int height(Node n) {
if (n == null)
return -1;
return n.height;
}
private void setBalance(Node... nodes) {
for (Node n : nodes)
reheight(n);
n.balance = height(n.right) - height(n.left);
}
public void printBalance() {
printBalance(root);
}
private void printBalance(Node n) {
if (n != null) {
printBalance(n.left);
System.out.printf("%s ", n.balance);
printBalance(n.right);
}
}
private void reheight(Node node){
if(node!=null){
node.height=1 + Math.max(height(node.left), height(node.right));
}
}
public static void main(String[] args) {
AVLTree tree = new AVLTree();
System.out.println("Inserting values 1 to 10");
for (int i = 1; i < 10; i++)
tree.insert(i);
System.out.print("Printing balance: ");
tree.printBalance();
}
}

View File

@ -1,268 +0,0 @@
/**
* This entire class is used to build a Binary Tree data structure.
* There is the Node Class and the Tree Class, both explained below.
*
* @author Unknown
*
*/
/**
* This class implements the nodes that will go on the Binary Tree.
* They consist of the data in them, the node to the left, the node
* to the right, and the parent from which they came from.
*
* @author Unknown
*
*/
class Node{
/** Data for the node */
public int data;
/** The Node to the left of this one */
public Node left;
/** The Node to the right of this one */
public Node right;
/** The parent of this node */
public Node parent;
/**
* Constructor of Node
*
* @param value Value to put in the node
*/
public Node(int value){
data = value;
left = null;
right = null;
parent = null;
}
}
/**
* A binary tree is a data structure in which an element
* has two successors(children). The left child is usually
* smaller than the parent, and the right child is usually
* bigger.
*
* @author Unknown
*
*/
class Tree{
/** The root of the Binary Tree */
private Node root;
/**
* Constructor
*/
public Tree(){
root = null;
}
/**
* Method to find a Node with a certain value
*
* @param key Value being looked for
* @return The node if it finds it, otherwise returns the parent
*/
public Node find(int key) {
Node current = root;
while (current != null) {
if(key < current.data) {
current = current.left;
} else if(key > current.data) {
current = current.right;
} else { // If you find the value return it
return current;
}
}
return null;
}
/**
* Inserts certain value into the Binary Tree
*
* @param value Value to be inserted
*/
public void put(int value){
Node newNode = new Node(value);
if(root == null)
root = newNode;
else{
//This will return the soon to be parent of the value you're inserting
Node parent = find(value);
//This if/else assigns the new node to be either the left or right child of the parent
if(value < parent.data){
parent.left = newNode;
parent.left.parent = parent;
return;
}
else{
parent.right = newNode;
parent.right.parent = parent;
return;
}
}
}
/**
* Deletes a given value from the Binary Tree
*
* @param value Value to be deleted
* @return If the value was deleted
*/
public boolean remove(int value){
//temp is the node to be deleted
Node temp = find(value);
//If the value doesn't exist
if(temp.data != value)
return false;
//No children
if(temp.right == null && temp.left == null){
if(temp == root)
root = null;
//This if/else assigns the new node to be either the left or right child of the parent
else if(temp.parent.data < temp.data)
temp.parent.right = null;
else
temp.parent.left = null;
return true;
}
//Two children
else if(temp.left != null && temp.right != null){
Node successor = findSuccessor(temp);
//The left tree of temp is made the left tree of the successor
successor.left = temp.left;
successor.left.parent = successor;
//If the successor has a right child, the child's grandparent is it's new parent
if(successor.right != null && successor.parent != temp){
successor.right.parent = successor.parent;
successor.parent.left = successor.right;
successor.right = temp.right;
successor.right.parent = successor;
}
if(temp == root){
successor.parent = null;
root = successor;
return true;
}
//If you're not deleting the root
else{
successor.parent = temp.parent;
//This if/else assigns the new node to be either the left or right child of the parent
if(temp.parent.data < temp.data)
temp.parent.right = successor;
else
temp.parent.left = successor;
return true;
}
}
//One child
else{
//If it has a right child
if(temp.right != null){
if(temp == root){
root = temp.right; return true;}
temp.right.parent = temp.parent;
//Assigns temp to left or right child
if(temp.data < temp.parent.data)
temp.parent.left = temp.right;
else
temp.parent.right = temp.right;
return true;
}
//If it has a left child
else{
if(temp == root){
root = temp.left; return true;}
temp.left.parent = temp.parent;
//Assigns temp to left or right side
if(temp.data < temp.parent.data)
temp.parent.left = temp.left;
else
temp.parent.right = temp.left;
return true;
}
}
}
/**
* This method finds the Successor to the Node given.
* Move right once and go left down the tree as far as you can
*
* @param n Node that you want to find the Successor of
* @return The Successor of the node
*/
public Node findSuccessor(Node n){
if(n.right == null)
return n;
Node current = n.right;
Node parent = n.right;
while(current != null){
parent = current;
current = current.left;
}
return parent;
}
/**
* Returns the root of the Binary Tree
*
* @return the root of the Binary Tree
*/
public Node getRoot(){
return root;
}
/**
* Prints leftChild - root - rightChild
*
* @param localRoot The local root of the binary tree
*/
public void inOrder(Node localRoot){
if(localRoot != null){
inOrder(localRoot.left);
System.out.print(localRoot.data + " ");
inOrder(localRoot.right);
}
}
/**
* Prints root - leftChild - rightChild
*
* @param localRoot The local root of the binary tree
*/
public void preOrder(Node localRoot){
if(localRoot != null){
System.out.print(localRoot.data + " ");
preOrder(localRoot.left);
preOrder(localRoot.right);
}
}
/**
* Prints rightChild - leftChild - root
*
* @param localRoot The local root of the binary tree
*/
public void postOrder(Node localRoot){
if(localRoot != null){
postOrder(localRoot.left);
postOrder(localRoot.right);
System.out.print(localRoot.data + " ");
}
}
}

View File

@ -1,100 +0,0 @@
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
import java.util.LinkedList;
public class FindHeightOfTree {
// Driver Program
public static void main(String[] args) {
Node tree = new Node(5);
tree.insert(3);
tree.insert(7);
tree.insert(1);
tree.insert(-1);
tree.insert(29);
tree.insert(93);
tree.insert(6);
tree.insert(0);
tree.insert(-5);
tree.insert(-6);
tree.insert(-8);
tree.insert(-1);
// A level order representation of the tree
tree.printLevelOrder();
System.out.println();
System.out.println("Height of the tree is: " + tree.findHeight());
}
}
/**
* The Node class which initializes a Node of a tree
* printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc
* findHeight: Returns the height of the tree i.e. the number of links between root and farthest leaf
*/
class Node {
Node left, right;
int data;
public Node(int data) {
this.data = data;
}
public void insert (int value) {
if (value < data) {
if (left == null) {
left = new Node(value);
}
else {
left.insert(value);
}
}
else {
if (right == null) {
right = new Node(value);
}
else {
right.insert(value);
}
}
}
public void printLevelOrder() {
LinkedList<Node> queue = new LinkedList<>();
queue.add(this);
while(!queue.isEmpty()) {
Node n = queue.poll();
System.out.print(n.data + " ");
if (n.left != null) {
queue.add(n.left);
}
if (n.right != null) {
queue.add(n.right);
}
}
}
public int findHeight() {
return findHeight(this);
}
private int findHeight(Node root) {
if (root.left == null && root.right == null) {
return 0;
}
else if (root.left != null && root.right != null) {
return 1 + Math.max(findHeight(root.left), findHeight(root.right));
}
else if (root.left == null && root.right != null) {
return 1 + findHeight(root.right);
}
else {
return 1 + findHeight(root.left);
}
}
}

View File

@ -1,226 +0,0 @@
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
public class treeclass {
private class Node {
int data;
ArrayList<Node> child = new ArrayList<>();
}
private Node root;
private int size;
/*
A generic tree is a tree which can have as many children as it can be
It might be possible that every node present is directly connected to
root node.
In this code
Every function has two copies: one function is helper function which can be called from
main and from that function a private function is called which will do the actual work.
I have done this, while calling from main one have to give minimum parameters.
*/
public treeclass() { //Constructor
Scanner scn = new Scanner(System.in);
root = create_treeG(null, 0, scn);
}
private Node create_treeG(Node node, int childindx, Scanner scn) {
// display
if (node == null) {
System.out.println("Enter root's data");
} else {
System.out.println("Enter data of parent of index " + node.data + " " + childindx);
}
// input
node = new Node();
node.data = scn.nextInt();
System.out.println("number of children");
int number = scn.nextInt();
for (int i = 0; i < number; i++) {
Node childd = create_treeG(node, i, scn);
size++;
node.child.add(childd);
}
return node;
}
/*
Function to display the generic tree
*/
public void display() { //Helper function
display_1(root);
return;
}
private void display_1(Node parent) {
System.out.print(parent.data + "=>");
for (int i = 0; i < parent.child.size(); i++) {
System.out.print(parent.child.get(i).data + " ");
}
System.out.println(".");
for (int i = 0; i < parent.child.size(); i++) {
display_1(parent.child.get(i));
}
return;
}
/*
One call store the size directly but if you are asked compute size this function to calcuate
size goes as follows
*/
public int size2call() {
return size2(root);
}
public int size2(Node roott) {
int sz = 0;
for (int i = 0; i < roott.child.size(); i++) {
sz += size2(roott.child.get(i));
}
return sz + 1;
}
/*
Function to compute maximum value in the generic tree
*/
public int maxcall() {
int maxi = root.data;
return max(root, maxi);
}
private int max(Node roott, int maxi) {
if (maxi < roott.data)
maxi = roott.data;
for (int i = 0; i < roott.child.size(); i++) {
maxi = max(roott.child.get(i), maxi);
}
return maxi;
}
/*
Function to compute HEIGHT of the generic tree
*/
public int heightcall() {
return height(root) - 1;
}
private int height(Node node) {
int h = 0;
for (int i = 0; i < node.child.size(); i++) {
int k = height(node.child.get(i));
if (k > h)
h = k;
}
return h + 1;
}
/*
Function to find whether a number is present in the generic tree or not
*/
public boolean findcall(int info) {
return find(root, info);
}
private boolean find(Node node, int info) {
if (node.data == info)
return true;
for (int i = 0; i < node.child.size(); i++) {
if (find(node.child.get(i), info))
return true;
}
return false;
}
/*
Function to calculate depth of generic tree
*/
public void depthcaller(int dep) {
depth(root, dep);
}
public void depth(Node node, int dep) {
if (dep == 0) {
System.out.println(node.data);
return;
}
for (int i = 0; i < node.child.size(); i++)
depth(node.child.get(i), dep - 1);
return;
}
/*
Function to print generic tree in pre-order
*/
public void preordercall() {
preorder(root);
System.out.println(".");
}
private void preorder(Node node) {
System.out.print(node.data + " ");
for (int i = 0; i < node.child.size(); i++)
preorder(node.child.get(i));
}
/*
Function to print generic tree in post-order
*/
public void postordercall() {
postorder(root);
System.out.println(".");
}
private void postorder(Node node) {
for (int i = 0; i < node.child.size(); i++)
postorder(node.child.get(i));
System.out.print(node.data + " ");
}
/*
Function to print generic tree in level-order
*/
public void levelorder() {
LinkedList<Node> q = new LinkedList<>();
q.addLast(root);
while (!q.isEmpty()) {
int k = q.getFirst().data;
System.out.print(k + " ");
for (int i = 0; i < q.getFirst().child.size(); i++) {
q.addLast(q.getFirst().child.get(i));
}
q.removeFirst();
}
System.out.println(".");
}
/*
Function to remove all leaves of generic tree
*/
public void removeleavescall() {
removeleaves(root);
}
private void removeleaves(Node node) {
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < node.child.size(); i++) {
if (node.child.get(i).child.size() == 0) {
arr.add(i);
// node.child.remove(i);
// i--;
} else
removeleaves(node.child.get(i));
}
for (int i = arr.size() - 1; i >= 0; i--) {
node.child.remove(arr.get(i) + 0);
}
}

View File

@ -1,78 +0,0 @@
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class LevelOrderTraversal
{
// Root of the Binary Tree
Node root;
public LevelOrderTraversal()
{
root = null;
}
/* function to print level order traversal of tree*/
void printLevelOrder()
{
int h = height(root);
int i;
for (i=1; i<=h; i++)
printGivenLevel(root, i);
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node root)
{
if (root == null)
return 0;
else
{
/* compute height of each subtree */
int lheight = height(root.left);
int rheight = height(root.right);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
/* Print nodes at the given level */
void printGivenLevel (Node root ,int level)
{
if (root == null)
return;
if (level == 1)
System.out.print(root.data + " ");
else if (level > 1)
{
printGivenLevel(root.left, level-1);
printGivenLevel(root.right, level-1);
}
}
/* Driver program to test above functions */
public static void main(String args[])
{
LevelOrderTraversal tree = new LevelOrderTraversal();
tree.root= new Node(1);
tree.root.left= new Node(2);
tree.root.right= new Node(3);
tree.root.left.left= new Node(4);
tree.root.left.right= new Node(5);
System.out.println("Level order traversal of binary tree is ");
tree.printLevelOrder();
}
}

View File

@ -1,62 +0,0 @@
import java.util.Queue;
import java.util.LinkedList;
/* Class to represent Tree node */
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = null;
right = null;
}
}
/* Class to print Level Order Traversal */
public class LevelOrderTraversalQueue {
Node root;
/* Given a binary tree. Print its nodes in level order
using array for implementing queue */
void printLevelOrder()
{
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while (!queue.isEmpty())
{
/* poll() removes the present head.
For more information on poll() visit
http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
Node tempNode = queue.poll();
System.out.print(tempNode.data + " ");
/*Enqueue left child */
if (tempNode.left != null) {
queue.add(tempNode.left);
}
/*Enqueue right child */
if (tempNode.right != null) {
queue.add(tempNode.right);
}
}
}
public static void main(String args[])
{
/* creating a binary tree and entering
the nodes */
LevelOrderTraversalQueue tree_level = new LevelOrderTraversalQueue();
tree_level.root = new Node(1);
tree_level.root.left = new Node(2);
tree_level.root.right = new Node(3);
tree_level.root.left.left = new Node(4);
tree_level.root.left.right = new Node(5);
System.out.println("Level order traversal of binary tree is - ");
tree_level.printLevelOrder();
}
}

View File

@ -1,105 +0,0 @@
// Java program to print top view of Binary tree
import java.util.*;
// Class for a tree node
class TreeNode
{
// Members
int key;
TreeNode left, right;
// Constructor
public TreeNode(int key)
{
this.key = key;
left = right = null;
}
}
// A class to represent a queue item. The queue is used to do Level
// order traversal. Every Queue item contains node and horizontal
// distance of node from root
class QItem
{
TreeNode node;
int hd;
public QItem(TreeNode n, int h)
{
node = n;
hd = h;
}
}
// Class for a Binary Tree
class Tree
{
TreeNode root;
// Constructors
public Tree() { root = null; }
public Tree(TreeNode n) { root = n; }
// This method prints nodes in top view of binary tree
public void printTopView()
{
// base case
if (root == null) { return; }
// Creates an empty hashset
HashSet<Integer> set = new HashSet<>();
// Create a queue and add root to it
Queue<QItem> Q = new LinkedList<QItem>();
Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
// Standard BFS or level order traversal loop
while (!Q.isEmpty())
{
// Remove the front item and get its details
QItem qi = Q.remove();
int hd = qi.hd;
TreeNode n = qi.node;
// If this is the first node at its horizontal distance,
// then this node is in top view
if (!set.contains(hd))
{
set.add(hd);
System.out.print(n.key + " ");
}
// Enqueue left and right children of current node
if (n.left != null)
Q.add(new QItem(n.left, hd-1));
if (n.right != null)
Q.add(new QItem(n.right, hd+1));
}
}
}
// Driver class to test above methods
public class PrintTopViewofTree
{
public static void main(String[] args)
{
/* Create following Binary Tree
1
/ \
2 3
\
4
\
5
\
6*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(4);
root.left.right.right = new TreeNode(5);
root.left.right.right.right = new TreeNode(6);
Tree t = new Tree(root);
System.out.println("Following are nodes in top view of Binary Tree");
t.printTopView();
}
}

View File

@ -1,124 +0,0 @@
import java.util.LinkedList;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
// Driver Program
public class TreeTraversal {
public static void main(String[] args) {
Node tree = new Node(5);
tree.insert(3);
tree.insert(2);
tree.insert(7);
tree.insert(4);
tree.insert(6);
tree.insert(8);
// Prints 5 3 2 4 7 6 8
System.out.println("Pre order traversal:");
tree.printPreOrder();
System.out.println();
// Prints 2 3 4 5 6 7 8
System.out.println("In order traversal:");
tree.printInOrder();
System.out.println();
// Prints 2 4 3 6 8 7 5
System.out.println("Post order traversal:");
tree.printPostOrder();
System.out.println();
// Prints 5 3 7 2 4 6 8
System.out.println("Level order traversal:");
tree.printLevelOrder();
System.out.println();
}
}
/**
* The Node class which initializes a Node of a tree
* Consists of all 4 traversal methods: printInOrder, printPostOrder printPreOrder & printLevelOrder
* printInOrder: LEFT -> ROOT -> RIGHT
* printPreOrder: ROOT -> LEFT -> RIGHT
* printPostOrder: LEFT -> RIGHT -> ROOT
* printLevelOrder: Prints by level (starting at root), from left to right.
*/
class Node {
Node left, right;
int data;
public Node(int data) {
this.data = data;
}
public void insert (int value) {
if (value < data) {
if (left == null) {
left = new Node(value);
}
else {
left.insert(value);
}
}
else {
if (right == null) {
right = new Node(value);
}
else {
right.insert(value);
}
}
}
public void printInOrder() {
if (left != null) {
left.printInOrder();
}
System.out.print(data + " ");
if (right != null) {
right.printInOrder();
}
}
public void printPreOrder() {
System.out.print(data + " ");
if (left != null) {
left.printPreOrder();
}
if (right != null) {
right.printPreOrder();
}
}
public void printPostOrder() {
if (left != null) {
left.printPostOrder();
}
if (right != null) {
right.printPostOrder();
}
System.out.print(data + " ");
}
/**
* O(n) time algorithm.
* Uses O(n) space to store nodes in a queue to aid in traversal.
*/
public void printLevelOrder() {
LinkedList<Node> queue = new LinkedList<>();
queue.add(this);
while (queue.size() > 0) {
Node head = queue.remove();
System.out.print(head.data + " ");
// Add children of recently-printed node to queue, if they exist.
if (head.left != null) {
queue.add(head.left);
}
if (head.right != null) {
queue.add(head.right);
}
}
}
}

View File

@ -1,135 +0,0 @@
//Trie Data structure implementation without any libraries */
/**
*
* @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92)
*
*/
import java.util.Scanner;
public class TrieImp {
public class TrieNode {
TrieNode[] child;
boolean end;
public TrieNode(){
child = new TrieNode[26];
end = false;
}
}
private final TrieNode root;
public TrieImp(){
root = new TrieNode();
}
public void insert(String word){
TrieNode currentNode = root;
for(int i=0; i < word.length();i++){
TrieNode node = currentNode.child[word.charAt(i)-'a'];
if(node == null){
node = new TrieNode();
currentNode.child[word.charAt(i)-'a']=node;
}
currentNode = node;
}
currentNode.end = true;
}
public boolean search(String word){
TrieNode currentNode = root;
for(int i=0;i<word.length();i++){
char ch = word.charAt(i);
TrieNode node = currentNode.child[ch-'a'];
if(node == null){
return false;
}
currentNode = node;
}
return currentNode.end;
}
public boolean delete(String word){
TrieNode currentNode = root;
for(int i=0;i<word.length();i++){
char ch = word.charAt(i);
TrieNode node = currentNode.child[ch-'a'];
if(node == null){
return false;
}
currentNode = node;
}
if(currentNode.end == true){
currentNode.end = false;
return true;
}
return false;
}
public static void sop(String print){
System.out.println(print);
}
//Regex to check if word contains only a-z character
public static boolean isValid(String word){
return word.matches("^[a-z]+$");
}
public static void main(String[] args) {
TrieImp obj = new TrieImp();
String word;
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
sop("string should contain only a-z character for all operation");
while(true){
sop("1. Insert\n2. Search\n3. Delete\n4. Quit");
try{
int t = scan.nextInt();
switch (t) {
case 1:
word = scan.next();
if(isValid(word))
obj.insert(word);
else
sop("Invalid string: allowed only a-z");
break;
case 2:
word = scan.next();
boolean resS=false;
if(isValid(word))
resS = obj.search(word);
else
sop("Invalid string: allowed only a-z");
if(resS)
sop("word found");
else
sop("word not found");
break;
case 3:
word = scan.next();
boolean resD=false;
if(isValid(word))
resD = obj.delete(word);
else
sop("Invalid string: allowed only a-z");
if(resD){
sop("word got deleted successfully");
}else{
sop("word not found");
}
break;
case 4:
sop("Quit successfully");
System.exit(1);
break;
default:
sop("Input int from 1-4");
break;
}
}catch(Exception e){
String badInput = scan.next();
sop("This is bad input: " + badInput);
}
}
}
}

View File

@ -1,62 +0,0 @@
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class ValidBSTOrNot
{
//Root of the Binary Tree
Node root;
/* can give min and max value according to your code or
can write a function to find min and max value of tree. */
/* returns true if given search tree is binary
search tree (efficient version) */
boolean isBST() {
return isBSTUtil(root, Integer.MIN_VALUE,
Integer.MAX_VALUE);
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
boolean isBSTUtil(Node node, int min, int max)
{
/* an empty tree is BST */
if (node == null)
return true;
/* false if this node violates the min/max constraints */
if (node.data < min || node.data > max)
return false;
/* otherwise check the subtrees recursively
tightening the min/max constraints */
// Allow only distinct values
return (isBSTUtil(node.left, min, node.data-1) &&
isBSTUtil(node.right, node.data+1, max));
}
/* Driver program to test above functions */
public static void main(String args[])
{
ValidBSTOrNot tree = new ValidBSTOrNot();
tree.root = new Node(4);
tree.root.left = new Node(2);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(3);
if (tree.isBST())
System.out.println("IS BST");
else
System.out.println("Not a BST");
}
}

View File

@ -1,59 +1,54 @@
public class CircleLinkedList<E>{
private static class Node<E>{
Node<E> next;
E value;
private Node(E value, Node<E> next){
this.value = value;
this.next = next;
}
}
//For better O.O design this should be private allows for better black box design
private int size;
//this will point to dummy node;
private Node<E> head;
private Node<E> tail;
//constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty;
public CircleLinkedList(){
head = new Node<>(null, head);
tail = head;
}
// getter for the size... needed because size is private.
public int getSize(){ return size;}
// for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really.
public void append(E value){
if(value == null){
// we do not want to add null elements to the list.
throw new NullPointerException("Cannot add null element to the list");
}
//add new node at the end of the list and update tail node to point to new node
tail.next = new Node(value, head);
tail = tail.next;
size++;
}
public E remove(int pos){
if(pos>=size || pos< 0){
//catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
Node<E> iterator = head.next;
//we need to keep track of the element before the element we want to remove we can see why bellow.
Node<E> before = head;
for(int i = 1; i<=pos; i++){
private static class Node<E>{
Node<E> next;
E value;
private Node(E value, Node<E> next){
this.value = value;
this.next = next;
}
}
//For better O.O design this should be private allows for better black box design
private int size;
//this will point to dummy node;
private Node<E> head;
//constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty;
public CircleLinkedList(){
//creation of the dummy node
head = new Node<E>(null,head);
size = 0;
}
// getter for the size... needed because size is private.
public int getSize(){ return size;}
// for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really.
public void append(E value){
if(value == null){
// we do not want to add null elements to the list.
throw new NullPointerException("Cannot add null element to the list");
}
//head.next points to the last element;
head.next = new Node<E>(value,head);
size++;}
public E remove(int pos){
if(pos>size || pos< 0){
//catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
Node<E> iterator = head.next;
//we need to keep track of the element before the element we want to remove we can see why bellow.
Node<E> before = head;
for(int i = 1; i<=pos; i++){
iterator = iterator.next;
before = before.next;
}
E removedValue = iterator.value;
// assigning the next reference to the the element following the element we want to remove... the last element will be assigned to the head.
before.next = iterator.next;
// scrubbing
iterator.next = null;
iterator.value = null;
size--;
before = before.next;
}
E saved = iterator.value;
// assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head.
before.next = iterator.next;
// scrubbing
iterator.next = null;
iterator.value = null;
return saved;
return removedValue;
}
}
}
}

View File

@ -15,6 +15,7 @@ class StackOfLinkedList {
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.printStack();
@ -23,6 +24,8 @@ class StackOfLinkedList {
stack.pop();
stack.pop();
System.out.println("Top element of stack currently is: " + stack.peek());
}
}
@ -75,12 +78,20 @@ class LinkedListStack {
System.out.println("Popped element is: " + temp.data);
}
public int peek() {
if (getSize() == 0) {
return -1;
}
return head.data;
}
public void printStack() {
Node temp = head;
System.out.println("Stack is printed as below: ");
while (temp != null) {
System.out.print(temp.data + " ");
System.out.println(temp.data + " ");
temp = temp.next;
}
System.out.println();
@ -94,5 +105,5 @@ class LinkedListStack {
public int getSize() {
return size;
}
}

View File

@ -53,16 +53,18 @@ class Stack{
* @return value popped off the Stack
*/
public int pop(){
if(isEmpty()){ //Checks for an empty stack
System.out.println("The stack is already empty");
return -1;
if(!isEmpty()){ //Checks for an empty stack
return stackArray[top--];
}
if(top < maxSize/4){
resize(maxSize/2);
return pop();// don't forget pop after resizing
}
else{
System.out.println("The stack is already empty");
return -1;
}
return stackArray[top--];
}
/**

View File

@ -19,19 +19,19 @@ public class TreeTraversal {
tree.insert(8);
// Prints 5 3 2 4 7 6 8
System.out.println("Preorder traversal:");
System.out.println("Pre order traversal:");
tree.printPreOrder();
System.out.println();
// Prints 2 3 4 5 6 7 8
System.out.println("Inorder traversal:");
System.out.println("In order traversal:");
tree.printInOrder();
System.out.println();
// Prints 2 4 3 6 8 7 5
System.out.println("Postorder traversal:");
System.out.println("Post order traversal:");
tree.printPostOrder();
System.out.println();
// Prints 5 3 7 2 4 6 8
System.out.println("Levelorder traversal:");
System.out.println("Level order traversal:");
tree.printLevelOrder();
System.out.println();
}
@ -39,7 +39,7 @@ public class TreeTraversal {
/**
* The Node class which initializes a Node of a tree
* Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder
* Consists of all 4 traversal methods: printInOrder, printPostOrder printPreOrder & printLevelOrder
* printInOrder: LEFT -> ROOT -> RIGHT
* printPreOrder: ROOT -> LEFT -> RIGHT
* printPostOrder: LEFT -> RIGHT -> ROOT