I call a method and it gives me an error - java

My source code:
import java.util.*;
public class Arvore {
public Arvore() {
root = null;
}
public void inserir(String x) {
root = insert(x, root);
}
public void remove(String x) {
root = remove(x, root);
}
private No remove(String x, No t) {
if (t == null) {
return t;
}
int comp = x.compareTo(t.str);
if (comp < 0) {
t.left = remove(x, t.left);
} else if (comp > 0) {
t.right = remove(x, t.right);
} else if (t.left != null && t.right != null) {
t.str = findMin(t.right).str;
t.right = remove(t.str, t.right);
} else {
t = (t.left != null) ? t.left : t.right;
}
return balance(t);
}
public String findMin() {
return findMin(root).str;
}
public String findMax() {
return findMax(root).str;
}
public boolean contains(String x) {
return contains(x, root);
}
public void makeEmpty() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
private static final int maxBal = 1;
private No balance(No t) {
if (t == null) {
return t;
}
if (height(t.left) - height(t.right) > maxBal) {
if (height(t.left.left) >= height(t.left.right)) {
t = rotateWithLeftChild(t);
} else {
t = doubleWithLeftChild(t);
}
} else if (height(t.right) - height(t.left) > maxBal) {
if (height(t.right.right) >= height(t.right.left)) {
t = rotateWithRightChild(t);
} else {
t = doubleWithRightChild(t);
}
}
t.height = Math.max(height(t.left), height(t.right)) + 1;
return t;
}
public void checkBalance() {
checkBalance(root);
}
private int checkBalance(No t) {
if (t == null) {
return -1;
}
if (t != null) {
int hl = checkBalance(t.left);
int hr = checkBalance(t.right);
if (Math.abs(height(t.left) - height(t.right)) > 1
|| height(t.left) != hl || height(t.right) != hr) {
System.out.println("OOPS!!");
}
}
return height(t);
}
private No insert(String x, No t) {
if (t == null) {
return new No(x, null, null);
}
int comp = x.compareTo(t.str);
if (comp < 0) {
t.left = insert(x, t.left);
} else if (comp > 0) {
t.right = insert(x, t.right);
} else
;
t.occ+=1;
return balance(t);
}
private No findMin(No t) {
if (t == null) {
return t;
}
while (t.left != null) {
t = t.left;
}
return t;
}
private No findMax(No t) {
if (t == null) {
return t;
}
while (t.right != null) {
t = t.right;
}
return t;
}
private boolean contains(String x, No t) {
while (t != null) {
int comp = x.compareTo(t.str);
if (comp < 0) {
t = t.left;
} else if (comp > 0) {
t = t.right;
} else {
return true;
}
}
return false;
}
private void printTree(No t) {
if (t != null) {
printTree(t.left);
System.out.println(t.str + ": " + t.occ);
printTree(t.right);
}
}
private int height(No t) {
return t == null ? -1 : t.height;
}
private No rotateWithLeftChild(No k2) {
No k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
k1.height = Math.max(height(k1.left), k2.height) + 1;
return k1;
}
private No rotateWithRightChild(No k1) {
No k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
k2.height = Math.max(height(k2.right), k1.height) + 1;
return k2;
}
private No doubleWithLeftChild(No k3) {
k3.left = rotateWithRightChild(k3.left);
return rotateWithLeftChild(k3);
}
private No doubleWithRightChild(No k1) {
k1.right = rotateWithLeftChild(k1.right);
return rotateWithRightChild(k1);
}
private class No {
No(String tStr) {
this(tStr, null, null);
}
No(String tStr, No lt, No rt) {
str = tStr;
left = lt;
right = rt;
height = 0;
occ = 1;
}
String str;
No left;
No right;
int height;
int occ = 0;
}
private No root;
public static void main(String[] args) {
Arvore t = new Arvore();
System.out.println("AVL TREE TEST\n");
String msg;
String[] inputs;
Scanner sc = new Scanner(System.in);
ArrayList palavras = new ArrayList();
int i = 0;
while (true) {
msg = sc.nextLine();
if (msg.equals("")) {
break;
}
inputs = msg.split(" ");
i = 0;
while (i < inputs.length) {
palavras.add(inputs[i]);
}
}
i = 0;
while (i < palavras.size()) {
if (palavras.get(i).equals("REMOVE")) {
palavras.remove(palavras.get(i));
palavras.remove(palavras.get(i + 1));
i += 2;
} else {
t.insert(palavras.get(i));
}
i++;
}
t.printTree();
}
}
I can't figure out why i have an error when i call insert and printTree, on the main function.
And i have a warning by adding a string to my arraylist, when i do palavras.add(inputs[i]).

Your loop:
i = 0;
while (i < inputs.length) {
palavras.add(inputs[i]);
}
is not incrementing i, so you will eventually run out of space for the array as you try to insert an infinite number of references to inputs[0].
The warning is because you are using a raw ArrayList. Try declaring palavras as:
ArrayList<String> palavras = new ArrayList<>(); // new ArrayList<String>(); if pre Java 7
Your other loop:
i = 0;
while (i < palavras.size()) {
if (palavras.get(i).equals("REMOVE")) {
palavras.remove(palavras.get(i));
palavras.remove(palavras.get(i + 1));
i += 2;
} else {
t.insert(palavras.get(i));
}
i++;
}
will generate an IndexOutOfBoundsException if the first branch of the if is taken when i == palavras.size() - 1 when it tries to remove the second element. Even if you are guaranteed that "REMOVE" is always followed by another element, you need to either reverse the order of the removals:
palavras.remove(palavras.get(i + 1));
palavras.remove(palavras.get(i));
or remove the element at i twice:
palavras.remove(palavras.get(i));
palavras.remove(palavras.get(i));
(because when you call remove() it moves all succeeding elements down one position in the array).
You are calling t.printTree() but, there is no such method defined in class Arvore; the method you did define takes a tree as an argument. Same thing with insert(): the actual method that's available takes a String and a No as arguments.

Related

how can I sort the class generic type when read from file with

I have this class and I read from file the data and my program is add the word and I count every word for example:
(WData{word=success, count=1} WData{word=automata, count=1} Data{word=theory, count=2}) How can I sort the output and start with character A to Z I mean the word and. this my code
Class Sa
class SA:
public class SA<T> {
int head;
int size;
T[] nodes;
public SA(int maxsize) {
head = 0;
nodes = (T[]) new Object[maxsize];
size = 0;
}
public int size() {
return size;}
public boolean empty() {
return size == 0;
public void insert(T e) {
nodes[size] = e;
size++;
}
public T find(T s) {
if (size != 0) {
for (int i = 0; i < size; i++) {
if (nodes[i].equals(s)) {
return nodes[i];
}
}
}
return null;
}
public void display() {
for (int i = 0; i < size; i++) {
System.out.println(nodes[i].toString());
}}}
and here class TextAnalyzer:
Public class TextAnalyzer<T> {
private static class WData {
#Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.word);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final WData other = (WData) obj;
if (!Objects.equals(this.word, other.word)) {
return false;
}
return true;
}
String word;
int count;
public WData(String w, int f) {
word = w;
count = f;
}
#Override
public String toString() {
return "WData{" + "word=" + word + ", count=" + count + '}';
}
} SA<WData>list;
public TextAnalyzer() {
list=new SA<WData>(11000);
}
public void processText(String filename) {
long count = 0;
try {
Scanner sc = new Scanner(new File(filename));;
while (sc.hasNext()) {
String line = sc.next();
String st = line.replaceAll("[^a-zA-Z ]", "").toLowerCase();
processWord(st);}
list.display();
} catch (FileNotFoundException ex) {
System.out.println("There are error in processText");
}
}
public void processWord(String word) {
WData w = new WData(word, 1);
WData s = list.find(w);
if (s == null) {
list.insert(w);
} else {
s.count = s.count + 1;
}}}

set.iterator().......where am i wrong?

Trying to implement a SET interface and to use an Iterator for the union method. Inside the union method it never enters the while loop. It does not add the elements from the parameter "set" that the union method has.
Any ideas? :)
package linkedSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import linkedList.LinearNode;
public class LinkedSet implements SetADT {
private int size;
private LinearNode<T> front;
private boolean allowNullElement = false;
// /////////////////////////////////////////////////////
private class LinkedSetIterator implements Iterator<T> {
private LinearNode<T> currentNode;
public LinkedSetIterator() {
currentNode = front;
}
#Override
public boolean hasNext() {
return currentNode == null;
}
#Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T temp = currentNode.getElement();
currentNode = currentNode.getNext();
return temp;
}
}
///////////////////////////////////////////////////
#Override
public Iterator<T> iterator() {
return new LinkedSetIterator();
}
public LinkedSet(boolean allowNullElement) {
size = 0;
front = new LinearNode<T>();
this.allowNullElement = allowNullElement;
}
public String toString() {
String str = "{";
for (int i = 0; i < size; i++) {
str += getNode(i).getElement();
if (i < size - 1) {
str += (", ");
}
}
return str + "}";
}
private LinearNode<T> getNode(int index) {
LinearNode<T> current = front;
for (int i = 0; i < index; i++) {
current = current.getNext();
}
return current;
}
#Override
public void add(T element) {
if (element == null && !allowNullElement) {
throw new IllegalArgumentException(
"Null element is not allowed to add");
}
front = new LinearNode<T>(element, front);
size++;
}
#Override
public T remove(T element) {
if (!(contains(element))) {
throw new IllegalStateException();
}
T temp = null;
;
for (int i = 0; i < size; i++) {
temp = getNode(i).getElement();
if (temp.equals(element) || temp == element) {
if (i == 0) {
front = front.getNext();
break;
} else {
getNode(i).setElement(front.getElement());
front = front.getNext();
break;
}
}
}
size--;
return temp;
}
#Override
public boolean contains(T element) {
for (int i = 0; i < size; i++) {
if (getNode(i).getElement() != null
&& getNode(i).getElement().equals(element)) {
return true;
}
if (getNode(i).getElement() == null
&& getNode(i).getElement() == element) {
return true;
}
}
return false;
}
#Override
public boolean isEmpty() {
return size == 0;
}
#Override
public int size() {
return size;
}
#Override
public boolean isSubset(SetADT<T> set) {
if (set == null) {
throw new IllegalArgumentException();
}
for (int i = 0; i < size; i++) {
T temp = getNode(i).getElement();
if (!(set.contains(temp))) {
return false;
}
}
return true;
}
#Override
public SetADT<T> intersection(SetADT<T> set) {
if (set == null) {
throw new IllegalArgumentException();
}
LinkedSet<T> temp = new LinkedSet<T>(allowNullElement);
for (int i = 0; i < size; i++) {
if (set.contains(getNode(i).getElement())) {
temp.add(getNode(i).getElement());
}
}
return temp;
}
public SetADT<T> union(SetADT<T> set) {
if (set == null) {
throw new IllegalArgumentException();
}
LinkedSet<T> temp = new LinkedSet<T>(allowNullElement);
LinearNode<T> node = front;
for (int i = 0; i < size; i++) {
T el = node.getElement();
temp.add(el);
node = node.getNext();
}
Iterator<T> iterator = set.iterator();
while (iterator.hasNext()) {
temp.add(iterator.next());
}
return temp;
}
}
The LinkedSetIterator.hasNext() method will return false if the set is nonempty. This could be corrected with inverting the condition:
#Override
public boolean hasNext() {
return currentNode != null;
}

Getting error: Incomparable types - Object and int

My code is below but when I build the project, Netbeat gives me this warning:
Error: incomparable types: Object and int
if (p.info == x) {
Does anyone know how to fix this error? Thanks.
Here's error code:
public void insert(int x) {
if (root == null) {
root = new Node(x);
return;
}
Node f, p;
p = root;
f = null;
while (p != null) {
if (p.info == x) {
System.out.println(" The key " + x + " already exists, no insertion");
return;
}
f = p;
if (x < (int) p.info) {
p = p.left;
} else {
p = p.right;
}
}
if (x < (int) f.info) {
f.left = new Node(x);
} else {
f.right = new Node(x);
}
}
Here's all the code I have so far:
package ass6;
import java.util.ArrayList;
public class Ass6 {
public static void main(String[] args) {
BinarySearchTree bsTree = new BinarySearchTree();
String[] c = {"C6", "C2", "C7", "C1", "C5", "C9", "C4", "C8", "C3"};
bsTree.insertMany(c);
System.out.println("Calculate level of all nodes:");
bsTree.breadth_first_traverse3();
System.out.println("");
bsTree.calLevel(bsTree.root, 1);
bsTree.breadth_first_traverse();
System.out.println("");
System.out.println("\nCalculate the height of the tree:");
bsTree.calheight(bsTree.root);
bsTree.breadth_first_traverse1();
System.out.println("");
System.out.println("Calculate balance factor of all nodes:");
bsTree.breadth_first_traverse3();
System.out.println("");
bsTree.calbaFactor(bsTree.root);
bsTree.breadth_first_traverse2();
bsTree.AVL(bsTree.root);
System.out.println("");
System.out.println("Balance a binary search tree:");
bsTree.breadth_first_traverse3();
System.out.println("");
bsTree.balance();
bsTree.breadth_first_traverse3();
System.out.println("");
}
}
class BinarySearchTree {
Node root;
int height;
int i;
void clear() {
root = null;
}
public BinarySearchTree() {
root = null;
}
Node search(Node p, int x) {
if (p == null) {
return (null);
}
if ((int) p.info == x) {
return (p);
}
if (x < (int) p.info) {
return (search(p.left, x));
} else {
return (search(p.right, x));
}
}
public void insertMany(int a[]) {
for (int x : a) {
insert(x);
}
}
public void insertMany(String a[]) {
for (String x : a) {
insert(x);
}
}
public void insert(String x) {
if (root == null) {
root = new Node(x);
return;
}
Node f, p;
p = root;
f = null;
while (p != null) {
if (p.info == x) {
System.out.println(" The key " + x + " already exists, no insertion");
return;
}
f = p;
if (x.compareTo(p.info.toString()) < 0) {
p = p.left;
} else {
p = p.right;
}
}
if (x.compareTo(f.info.toString()) < 0) {
f.left = new Node(x);
} else {
f.right = new Node(x);
}
}
public void insert(int x) {
if (root == null) {
root = new Node(x);
return;
}
Node f, p;
p = root;
f = null;
while (p != null) {
if (p.info == x) {
System.out.println(" The key " + x + " already exists, no insertion");
return;
}
f = p;
if (x < (int) p.info) {
p = p.left;
} else {
p = p.right;
}
}
if (x < (int) f.info) {
f.left = new Node(x);
} else {
f.right = new Node(x);
}
}
public void visitLevel(Node x) {
System.out.print("(" + x.info + "," + x.level + "), ");
}
public void visit(Node x) {
System.out.print(x.info + ", ");
}
public void visitheight(Node x) {
System.out.print("(" + x.info + "," + x.height + "), ");
}
public void visitbafator(Node x) {
System.out.print("(" + x.info + "," + x.baFactor + "), ");
}
public void breadth_first_traverse() {
MyQueue queue = new MyQueue();
Node p = root;
if (p != null) {
queue.enqueue(p);
}
while (!queue.isEmpty()) {
Node q = (Node) queue.dequeue();
visitLevel(q);
if (q.left != null) {
queue.enqueue(q.left);
}
if (q.right != null) {
queue.enqueue(q.right);
}
}
}
public void breadth_first_traverse1() {
MyQueue queue = new MyQueue();
Node p = root;
if (p != null) {
queue.enqueue(p);
}
while (!queue.isEmpty()) {
Node q = (Node) queue.dequeue();
visitheight(q);
if (q.left != null) {
queue.enqueue(q.left);
}
if (q.right != null) {
queue.enqueue(q.right);
}
}
System.out.println("");
}
public void breadth_first_traverse2() {
MyQueue queue = new MyQueue();
Node p = root;
if (p != null) {
queue.enqueue(p);
}
while (!queue.isEmpty()) {
Node q = (Node) queue.dequeue();
visitbafator(q);
if (q.left != null) {
queue.enqueue(q.left);
}
if (q.right != null) {
queue.enqueue(q.right);
}
}
System.out.println("");
}
public void breadth_first_traverse3() {
MyQueue queue = new MyQueue();
Node p = root;
if (p != null) {
queue.enqueue(p);
}
while (!queue.isEmpty()) {
Node q = (Node) queue.dequeue();
visit(q);
if (q.left != null) {
queue.enqueue(q.left);
}
if (q.right != null) {
queue.enqueue(q.right);
}
}
}
public void inorder(Node x) {
if (x == null) {
return;
}
inorder(x.left);
visit(x);
inorder(x.right);
}
public void calLevel(Node n, int i) {
if (n.left == null && n.right == null) {
n.level = i;
} else {
n.level = i;
if (n.left != null) {
calLevel(n.left, i + 1);
}
if (n.right != null) {
calLevel(n.right, i + 1);
}
}
}
public int treeheight(Node p) {
if (p == null) {
return 0;
}
int left = treeheight(p.left);
int right = treeheight(p.right);
return 1 + Math.max(left, right);
}
public void calheight(Node n) {
if (n.left == null && n.right == null) {
n.height = 1;
} else {
n.height = treeheight(n);
if (n.left != null) {
calheight(n.left);
}
if (n.right != null) {
calheight(n.right);
}
}
}
public void calbaFactor(Node n) {
if (n.left == null && n.right == null) {
n.baFactor = 0;
} else {
n.baFactor = treeheight(n.right) - treeheight(n.left);
if (n.baFactor > 1 || n.baFactor < -1) {
i++;
}
if (n.left != null) {
calbaFactor(n.left);
}
if (n.right != null) {
calbaFactor(n.right);
}
}
}
public void AVL(Node n) {
if (i > 0) {
System.out.println("The tree is not an AVL tree .");
} else {
System.out.println("The tree is an AVL tree .");
}
}
void inOrder(ArrayList<String> t, Node p) {
if (p == null) {
return;
}
inOrder(t, p.left);
t.add((String) p.info);
inOrder(t, p.right);
}
void balance(ArrayList<String> t, int i, int j) {
if (i > j) {
return;
}
int k = (i + j) / 2;
String x = t.get(k);
insert(x);
balance(t, i, k - 1);
balance(t, k + 1, j);
}
void balance() {
ArrayList<String> t = new ArrayList<>();
inOrder(t, root);
int n = t.size();
clear();
balance(t, 0, n - 1);
}
}
class Node {
Object info;
int level = 1;
int height = 0;
int baFactor = 0;
Node left, right;
public Node(Object inf, Node le, Node ri) {
info = inf;
left = le;
right = ri;
}
public Node(Object inf) {
info = inf;
left = right = null;
}
}
class MyQueue {
ArrayList al = new ArrayList();
MyQueue() {
}
public void enqueue(Object x) {
al.add(x);
}
public Object dequeue() {
Object obj = al.get(0);
al.remove(0);
return obj;
}
public boolean isEmpty() {
if (al.size() <= 0) {
return true;
} else {
return false;
}
}
}
In java, you cannot compare primitive types (int, float, double, byte etc) with instance types (everything derived from Object and then instantiated).
Use p.info.equals(x)
here p.info is an Object,and x is an int so you cannot simply compare with ==. but
.equals will work, becase the value will be compared.
Object obj = Integer.valueOf(3);
int x=3;
if ( obj.equals(x) ) { // true
}

writing a recursive method into a non recursive (java)

I'm a little bit confused as to understanding how recursion works.
Basically I have to replace recursive methods with non recursive methods.
For example, this is the recursive method:
public Key min() {
if (isEmpty()) {
return null;
}
return min(root).key;
}
private Node min(Node x) {
if (x.left == null) {
return x;
} else {
return min(x.left);
}
}
public Key max() {
if (isEmpty()) {
return null;
}
return max(root).key;
}
private Node max(Node x) {
if (x.right == null) {
return x;
} else {
return max(x.right);
}
}
public Key floor(Key key) {
Node x = floor(root, key);
if (x == null) {
return null;
} else {
return x.key;
}
}
private Node floor(Node x, Key key) {
if (x == null) {
return null;
}
int cmp = key.compareTo(x.key);
if (cmp == 0) {
return x;
}
if (cmp < 0) {
return floor(x.left, key);
}
Node t = floor(x.right, key);
if (t != null) {
return t;
} else {
return x;
}
}
public Key ceiling(Key key) {
Node x = ceiling(root, key);
if (x == null) {
return null;
} else {
return x.key;
}
}
private Node ceiling(Node x, Key key) {
if (x == null) {
return null;
}
int cmp = key.compareTo(x.key);
if (cmp == 0) {
return x;
}
if (cmp < 0) {
Node t = ceiling(x.left, key);
if (t != null) {
return t;
} else {
return x;
}
}
return ceiling(x.right, key);
}
And this is my attempt of doing it non-recursively:
public Key min() {
if (isEmpty()) {
return null;
}
return min(root).key;
}
private Node min(Node x) {
while (x.left !=null){
x = x.left;
}
return x;
}
public Key max() {
if (isEmpty()) {
return null;
}
return max(root).key;
}
private Node max(Node x) {
while (x.right!=null){
x = x.right;
}
return x;
}
public Key floor(Key key) {
Node x = floor(root, key);
if (x == null) {
return null;
} else {
return x.key;
}
}
private Node floor(Node x, Key key) {
if (x == null) {
return null;
}
int cmp = key.compareTo(x.key);
if (cmp == 0) {
return x;
}
if (cmp < 0) {
while (x.left != null){
x = x.left;
if (x ==null){
return null;
}
}
}
Node t = x.right;
while (x.right != null){
x = x.right;
if (x == null){
return null;
}
}
if (t != null){
return t;
}
else{
return x;
}
}
I'm just asking if I have the right idea.
Yes, you have the right idea.
private Node min(Node x) {
if (x.left == null) {
return x;
} else {
return min(x.left);
}
}
This is good non-recursive solution of the function above.
private Node min(Node x) {
while (x.left !=null){
x = x.left;
}
return x;
}
You should take a look at http://en.wikipedia.org/wiki/Dynamic_programming, particularly Memoization.
Edit: Also take a look at similar thread: Way to go from recursion to iteration

Array-based implementation of a sorted linked list

I need to write a java linked list which needs to be array based and sorted. So the array contains nodes which have 2 fields: the data, and the index of the next element in the list. The last element of the list needs to have an index of -1.
Can someone help how to add an element to such list. this is the code I wrote so far but does not seems to be right because I can add elements but the indexes are not right.
package listpackage;
import java.io.IOException;
public class ArrayLL {
private int MAX_CAP = 100;
private ANode[] list;
private int size;
public ArrayLL(){
list = new ANode[MAX_CAP];
list[list.length-1] = new ANode(null, -1);
for(int i = 0; i < list.length-1; i++){
list[i] = new ANode(null, i+1);
}
size = 0;
}
public void addElem(String s) throws IOException{
if(this.getSize() == 0){
ANode a = new ANode(s, -1);
list[0] = a;
}else if(size == MAX_CAP + 1){
throw new IOException("List is full");
}else{
int index = 0;
for(int i=0; i < list.length; i++){
if(list[i].getData() == null){
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if(this.getSize()==1){
if (list[index].getData().compareTo(list[0].getData()) < 0){
list[index].setLink(0);
list[0].setLink(-1);
}else{
list[index].setLink(-1);
list[0].setLink(index);
}
}else{
int i = 0;
while(list[i].getData() != null){
if(list[index].getData().compareTo(list[i].getData()) < 0){
list[index].setLink(i);
if(i>0)
list[i-1].setLink(index);
}else{
i++;
}
}
}
}
size++;
}
public ANode[] getList(){
return list;
}
public int getSize(){
return size;
}
}
class ANode{
private String data;
private int link;
public ANode(String d){
data = d;
link = -1;
}
public ANode(String d, int l){
data = d;
link = l;
}
public String getData(){
return data;
}
public int getLink(){
return link;
}
public void setLink(int l){
link = l;
}
}
It was fun to solve this tricky program... :-)... i enjoyed it...here is the working solution...I tested using various scenarios...
In order to make sure I do not change much of your code...I did not optimize the code..there are many places where code can be more simpler and readable...
import java.io.IOException;
public class ArrayLL {
public static void main(String[] args) throws IOException {
ArrayLL myList = new ArrayLL();
myList.addElem("c");
myList.addElem("b");
myList.addElem("a");
myList.addElem("d");
int i = myList.startOfListIndex;
while(myList.list[i].getLink()!=-1)
{
System.out.println(myList.list[i].getData());
i = myList.list[i].getLink();
}
System.out.println(myList.list[i].getData());
}
private int MAX_CAP = 100;
private ANode[] list;
private int size;
private int startOfListIndex = 0;
public ArrayLL() {
list = new ANode[MAX_CAP];
for (int i = 0; i < list.length; i++) {
list[i] = new ANode(null);
}
size = 0;
}
public void addElem(String s) throws IOException {
if (this.getSize() == 0) {
ANode a = new ANode(s, -1);
list[0] = a;
} else if (size == MAX_CAP + 1) {
throw new IOException("List is full");
} else {
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getData() == null) {
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if (this.getSize() == 1) {
if (list[index].getData().compareTo(list[0].getData()) < 0) {
list[index].setLink(0);
list[0].setLink(-1);
startOfListIndex = index;
} else {
list[index].setLink(-1);
list[0].setLink(index);
}
} else {
int i = startOfListIndex;
int prevIndex = -1;
while (i!=-1 && list[i].getData() != null) {
if (list[index].getData().compareTo(list[i].getData()) < 0) {
list[index].setLink(i);
if(prevIndex!=-1)
list[prevIndex].setLink(index);
else
startOfListIndex = index;
break;
} else {
prevIndex = i;
i=list[i].getLink();
}
}
if(i==-1)
{
list[prevIndex].setLink(index);
}
}
}
size++;
}
public ANode[] getList() {
return list;
}
public int getSize() {
return size;
}
}
class ANode {
private String data;
private int link;
public ANode(String d) {
data = d;
link = -1;
}
public ANode(String d, int l) {
data = d;
link = l;
}
public String getData() {
return data;
}
public int getLink() {
return link;
}
public void setLink(int l) {
link = l;
}
}
This is the full solution i believe as it works for all the test i have done, but there might be something i haven't thought of. The solution includes the removeElem() method too.
package listpackage;
import java.io.IOException;
public class ArrayLL {
private int MAX_CAP = 100;
private ANode[] list;
private int size;
private int startOfListIndex = 0;
public ArrayLL() {
list = new ANode[MAX_CAP];
list[list.length-1] = new ANode(null, -1);
for(int i = 0; i < list.length-1; i++){
list[i] = new ANode(null, i+1);
}
size = 0;
}
public void addElem(String s) throws IOException {
if (this.getSize() == 0) {
ANode a = new ANode(s, -1);
list[0] = a;
}else if (size == MAX_CAP + 1) {
throw new IOException("List is full");
}else{
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getData() == null) {
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if (this.getSize() == 1) {
if (list[index].getData().compareTo(list[0].getData()) < 0) {
list[index].setLink(0);
list[0].setLink(-1);
startOfListIndex = index;
} else {
list[index].setLink(-1);
list[0].setLink(index);
}
} else {
int i = startOfListIndex;
int prevIndex = -1;
while (i!=-1 && list[i].getData() != null) {
if (list[index].getData().compareTo(list[i].getData()) < 0) {
list[index].setLink(i);
if(prevIndex!=-1)
list[prevIndex].setLink(index);
else
startOfListIndex = index;
break;
}else{
prevIndex = i;
i=list[i].getLink();
}
}
if(i==-1)
{
list[prevIndex].setLink(index);
}
}
}
size++;
}
public void removeElem(String s) throws IOException {
if (this.getSize() == 0) {
throw new IOException("List is empty");
}else{
int firstEmpty = 0;
for(int i = 0; i< list.length; i++){
if(list[i].getData() == null){
firstEmpty = i;
break;
}
}
int elemindex = 0;
int prev = -1;
int next=-1;
for(int i = 0; i < list.length; i++){
if(list[i].getData() != null && list[i].getData().compareTo(s) == 0){
elemindex = i;
next = list[i].getLink();
for(int j = 0; j < list.length; j++){
if(list[j].getLink() == elemindex){
prev = j;
break;
}
}
list[elemindex].setDataNull();
list[elemindex].setLink(firstEmpty);
if(next != -1)
list[prev].setLink(next);
else
list[prev].setLink(-1);
size--;
}else{
elemindex++;
}
}
}
}
public ANode[] getList() {
return list;
}
public int getSize() {
return size;
}
}
class ANode {
private String data;
private int link;
public ANode(String d) {
data = d;
link = -1;
}
public ANode(String d, int l) {
data = d;
link = l;
}
public String getData() {
return data;
}
public void setDataNull(){
this.data = null;
}
public int getLink() {
return link;
}
public void setLink(int l) {
link = l;
}
}

Categories

Resources