LinkedQueue next value doesn't work as indeed - java

I want to create a Queue after the FIFO rule, every element is created at the end of the queue but my getNext() for the element don't work(the Value is null) and I have no clue.
Here is the UML:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyLinkedQueue<E> implements Iterable<E>, MyQueue<E> {
private Cell front;
private Cell rear;
private int count;
public Cell getFront() {
return front;
}
public void setFront(Cell front) {
this.front = front;
}
public Cell getRear() {
return rear;
}
public void setRear(Cell rear) {
this.rear = rear;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public class Cell {
private E value;
private Cell next;
Cell(E element) {
this.value = element;
}
public E getValue() {
return value;
}
public void setValue(E value) {
this.value = value;
}
public Cell getNext() {
return next;
}
public void setNext(Cell next) {
this.next = next;
}
}
public class MyIterator implements Iterator<E> {
private Cell pointer;
private boolean begin;
private boolean removable;
public Cell getPointer() {
return pointer;
}
public void setPointer(Cell pointer) {
this.pointer = pointer;
}
public boolean isBegin() {
return begin;
}
public void setBegin(boolean begin) {
this.begin = begin;
}
public boolean isRemovable() {
return removable;
}
public void setRemovable(boolean removable) {
this.removable = removable;
}
public MyIterator() {
}
public boolean hasNext() {
return pointer != null ? true : false;
}
public E next() {
if (!hasNext())
throw new NoSuchElementException();
E e = pointer.value;
pointer = pointer.getNext();
return e;
}
public void remove() {
throw new NoSuchElementException();
}
}
public boolean isEmpty() {
return count == 0;
}
public E peek() throws NoSuchElementException {
E result = null;
if (isEmpty()) {
System.out.println("Queue is empty");
} else {
result = front.getValue();
}
return result;
}
public E peekLast() throws NoSuchElementException {
E result = null;
if (isEmpty()) {
System.out.println("Queue is empty");
} else {
result = rear.getValue();
}
return result;
}
public MyQueue<E> append(E element) {
if (front == null)
front = new Cell(element);
rear = new Cell(element);
// rear=rear.getNext(); getNext() PROBLEM
count++;
return this;
}
public E delete() throws NoSuchElementException {
E e;
e = front.getValue();
// front = front.getNext();getNext() PROBLEM
count--;
if (count == 0)
rear = null;
return e;
}
public int size() {
return count;
}
public String toString() {
StringBuilder s = new StringBuilder();
for (E e : this)
s.append(e + "; ");
return s.toString();
}
#Override
public Iterator<E> iterator() {
Iterator<E> iterator = new MyIterator();
return iterator;
}
}

Related

Time out issue in java

I have been running this code and it seems like it times out. I'm not sure how to fix it as it doesn't show me an actual error message or anything like that. The first block of code is the class that the methods in the demo are coming from, and it seems like all the methods that are being called for stringList are just not working. When I test the same thing with an int list it works fine.
public class DoublyLinkedList<E> {
private static class Node<E> {
// Node Fields
private E element; //data
private Node<E> prev; //previous Node
private Node<E> next; //next Node
// Node Constructor
public Node(E e, Node<E> p, Node<E> n) {
this.element = e;
this.prev = p;
this.next = n;
}
// Node Methods
public E getElement() {
return element;
}
public Node<E> getPrev() {
return this.prev;
}
public Node<E> getNext() {
return this.next;
}
public void setPrev(Node<E> p) {
this.prev = p;
}
public void setNext(Node<E> n) {
this.next = n;
}
}
// DLinkedList Fields
private Node<E> header;
private Node<E> trailer;
int size;
// DLinkedList Constructor
public DoublyLinkedList() {
this.header = new Node<>(null, null, null);
this.trailer = new Node<>(null, this.header, null);
this.header.setNext(this.trailer);
}
// DLinkedList Methods
public int size() {
return this.size;
}
public E first() {
if (isEmpty()) {
return null;
}
return this.header.next.getElement();
}
public E last () {
if (isEmpty()) {
return null;
}
return this.trailer.prev.getElement();
}
public boolean isEmpty() {
return size == 0;
}
public void addFirst (E e) {
addBetween(e, this.header, this.header.getNext());
}
public void addLast (E e) {
addBetween(e, this.trailer.getPrev(), this.trailer);
}
private void addBetween(E e, Node<E> predecessor, Node<E> successor) {
Node<E> newest = new Node<>(e, predecessor, successor);
predecessor.setNext(newest);
successor.setPrev(newest);
this.size++;
}
public E removeFirst() {
if (this.isEmpty()) {
return null;
}
return this.remove(header.getNext());
}
public E removeLast() {
if (this.isEmpty()) {
return null;
}
return this.remove(trailer.getPrev());
}
public E remove(Node<E> e) {
e.next.setPrev(e.prev);
e.prev.setNext(e.next);
this.size--;
return e.getElement();
}
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node<E> walk = this.header.next;
while (walk != this.trailer) {
sb.append(walk.element);
if (walk.next != this.trailer)
sb.append(", ");
walk = walk.next;
}
sb.append(")");
return sb.toString();
}
//DONE
public void add(int index, E element) {
Node<E> pred = header;
Node<E> succ = pred.getNext();
int count = 0;
while(succ != null) {
if(count == index) addBetween(element, pred, succ);
count++;
pred = pred.getNext();
succ = succ.getNext();
}
}
//DONE
public void add(E e) {
add(size, e);
}
//DONE
public void clear() {
while(!isEmpty()) {
removeFirst();
}
}
public E get(int index) {
if (isEmpty()) return null;
Node<E> current = header;
int count = 0;
while(current != null) {
if(count == index) return current.getElement();
count++;
current = current.getNext();
}
return null;
}
public E set(int index, E element) {
if(isEmpty()) return null;
Node<E> current = header;
E returnVal = null;
int count = 0;
while(current != null) {
if(count == index) {
if(count == 0) {
returnVal = get(0);
removeFirst();
add(0, element);
}
else if(count == size) {
returnVal = get(size);
removeLast();
add(size, element);
}
else {
returnVal = get(index);
remove(current);
add(index, element);
}
}
}
return returnVal;
}
}
package labs;
public class DoublyLinkedListDemo {
public static void main(String[] args) {
//testing methods on a String DoublyList
DoublyLinkedList<String> stringList = new DoublyLinkedList<>();
stringList.addFirst("Strawberry");
stringList.addFirst("Banana");
stringList.addFirst("Apple");
stringList.set(0, stringList.get(1));
System.out.println(stringList);
stringList.add(1, "Pear");
System.out.println(stringList);
stringList.add("Blueberry");
System.out.println(stringList);
System.out.println(stringList.get(1));
stringList.clear();
System.out.println(stringList);
System.out.println(stringList.set(0, stringList.get(1)));
System.out.println(stringList.get(0));
}
}

Implement multiset using sorted linkedList

Hello I implemented a multiset using a linkedlist and I want to implement the multiset using sorted linkedlist. This is multiset abstract class.
import java.io.PrintStream;
public abstract class Multiset<T> {
/**
* Delimiter string for print operation.
*/
protected static final String printDelim = " | ";
public abstract void add(T item);
public abstract int search(T item);
public abstract void removeOne(T item);
public abstract void removeAll(T item);
public abstract void print(PrintStream out);
}
This is my implementation of linkedlist.
import java.io.PrintStream;
public class LinkedListMultiset<T> extends Multiset<T> {
protected Node mHead;
protected int mLength;
public LinkedListMultiset() {
// Implement me!
mHead = null;
mLength = 0;
}
public void add(T item) {
Node newNode = new Node((String) item);
if (mHead == null)
mHead = newNode;
else {
Node currNode = mHead;
Node parentNode = null;
while (currNode != null) {
if (currNode.getValue().
equals(newNode.getValue())) {
currNode.addCounter();
return;
}
parentNode = currNode;
currNode = currNode.getNext();
}
parentNode.setNext(newNode);
}
mLength++;
}
public int search(T item) {
Node currNode = mHead;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
return currNode.getCounter();
}
currNode = currNode.getNext();
}
return 0;
}
public void removeOne(T item) {
Node currNode = mHead;
Node lastNode = null;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
currNode.minusCounter();
if (currNode.getCounter() == 0) {
if (currNode == mHead)
mHead = currNode.getNext();
else
lastNode.setNext
(currNode.getNext());
mLength--;
}
return;
}
lastNode = currNode;
currNode = currNode.getNext();
}
}
public void removeAll(T item) {
Node currNode = mHead;
Node lastNode = null;
while (currNode != null) {
if (currNode.getValue().equals((String) item)) {
if (currNode == mHead)
mHead = currNode.getNext();
else
lastNode.setNext(currNode.getNext());
mLength--;
return;
}
lastNode = currNode;
currNode = currNode.getNext();
}
}
public void print(PrintStream out) {
Node currNode = mHead;
while (currNode != null) {
out.printf("%s | %d\n", currNode.getValue()
, currNode.getCounter());
currNode = currNode.getNext();
}
}
private class Node {
protected String mValue;
protected Node mNext;
int counter;
public Node(String value) {
mValue = value;
mNext = null;
counter = 1;
}
public void addCounter() {
counter++;
}
public void minusCounter() {
counter--;
}
public int getCounter() {
return counter;
}
public String getValue() {
return mValue;
}
public Node getNext() {
return mNext;
}
public void setValue(String value) {
mValue = value;
}
public void setNext(Node next) {
mNext = next;
}
}
}
I want to implement sorted linkedlist but I want to change my code as minimum as possible.

how to make an .add method which adding objects in a reference based list in alphabetically order

This is my user class and i found that i have to use the compareTo method but i need a method which adding in a Rb list.
There is an already existed add method and i have make a similar which order the users alphabetically.
import java.lang.Comparable;
public class LaptopUser implements Comparable<LaptopUser>
{
private String username;
private String password;
public LaptopUser(String username,String password)
{
this.username=username;
this.password=password;
}
public String getUsername(){
return username ;
}
public String getPass()
{
return password;
}
public String toString(){
return(username+","+password);
}
#Override
public int compareTo(LaptopUser n)
{
if(this.toString().compareTo(n.toString())>0)
{
return 1;
}
else if(this.toString().compareTo(n.toString())<0)
{
return -1;
}
return 0;
}
public boolean equals(LaptopUser p)
{
return(this.toString().equals(p.toString()));
}
}
public class ReferenceBasedList implements ListInterface
{
private ListNode head;
private ListNode tail;
int numItems;
public ReferenceBasedList()
{
head = tail = null;
numItems = 0;
}
public int size()
{
return numItems;
}
public boolean isEmpty()
{
return (numItems == 0);
}
public void removeAll()
{
head = tail = null;
numItems = 0;
}
private ListNode find(int index)
{
ListNode curr = head;
for (int skip = 1; skip < index; skip++)
curr = curr.getNext();
return curr;
}
public Object get(int index)
throws ListIndexOutOfBoundsException
{
if (index >= 1 && index <= numItems)
{
ListNode curr = find(index);
return curr.getItem();
}
else
{
throw new ListIndexOutOfBoundsException(
"List index out of bounds exception on get");
}
}
public void add(int index, Object newDataItem)
throws ListIndexOutOfBoundsException
{
if (index >= 1 && index <= numItems+1)
{
if ( index == 1 )
{
ListNode newNode = new ListNode(newDataItem, head);
head = newNode;
if (tail==null)
tail = head;
}
else if ( index==numItems+1 )
{
ListNode newNode = new ListNode(newDataItem);
tail.setNext(newNode);
tail = newNode;
}
else
{
ListNode prev = find(index-1);
ListNode newNode = new ListNode(newDataItem, prev.getNext());
prev.setNext(newNode);
}
numItems++;
}
else
{
throw new ListIndexOutOfBoundsException(
"List index out of bounds exception on add");
}
}
public void insert(Object newDataItem)
{
this.add(1,newDataItem);
}
public void append(Object newDataItem)
{
this.add(numItems+1,newDataItem);
}
public Object showFront()
{
return this.get(1);
}
public Object showLast()
{
return this.get(numItems);
}
public void remove(int index)
throws ListIndexOutOfBoundsException
{
if (index >= 1 && index <= numItems)
{
if (index == 1)
{
head = head.getNext();
if (head == null)
tail = null;
}
else
{
ListNode prev = find(index-1);
ListNode curr = prev.getNext();
prev.setNext(curr.getNext());
if (index == numItems)
tail = prev;
}
numItems--;
}
else
{
throw new ListIndexOutOfBoundsException(
"List index out of bounds exception on remove");
}
}
public boolean exists(Object dataItem)
{
for (ListNode tmp=head; tmp!=null; tmp=tmp.getNext())
if (tmp.getItem().equals(dataItem))
return true;
return false;
}
public Object removeLast() throws ListException
{
if (isEmpty())
throw new ListException("The linked list is empty");
else
{
Object lastDataItem = tail.getItem();
if (head == tail)
head = tail = null;
else
{
ListNode tmp = head;
while (tmp.getNext().getNext() != null)
tmp = tmp.getNext();
tail = tmp;
tail.setNext(null);
}
numItems--;
return lastDataItem;
}
}
public Object removeFront() throws ListException
{
if (isEmpty())
throw new ListException("The linked list is empty");
else
{
Object frontDataItem = head.getItem();
head = head.getNext();
if (head == null)
tail = null;
numItems--;
return frontDataItem;
}
}
}
You can use the Collections.binarySearch method to find at what index a LaptopUser should be added to a List in order for it to be alphabetically ordered.
SortedList:
public class SortedList implements Iterable<LaptopUser> {
public List<LaptopUser> users = new ArrayList<LaptopUser>();
public void add(LaptopUser user) {
int index = Collections.binarySearch(users, user);
if (index < 0)
users.add(-index - 1, user);
else
users.add(index, user);
}
#Override
public Iterator<LaptopUser> iterator() {
return users.iterator();
}
Example Code:
public class LaptopUser implements Comparable<LaptopUser> {
public String username;
public String password;
public LaptopUser(String username, String password) {
this.username = username;
this.password = password;
}
#Override
public int compareTo(LaptopUser o) {
return toString().compareTo(o.toString());
}
#Override
public String toString() {
return username.concat(password);
}
}
public Sorted() {
LaptopUser a =new LaptopUser("a", "password");
LaptopUser b =new LaptopUser("b", "password");
LaptopUser c =new LaptopUser("c", "password");
SortedList list = new SortedList();
list.add(c);
list.add(a);
list.add(b);
for(LaptopUser user : list)
System.out.println(user);
}
public static void main(String[] args) {
new Sorted();
}
Output:
apassword
bpassword
cpassword

How I have to return in "next" method of Iterator<E>?

in method "next" implemented in Iterator there is a mistake. I cannot return 'e' value, because Java says it is Object type. I don't understand why. Because in Elem class if I give for instance Point object, it must return it. But I don't know generics well, maybe someone could explain plz. Thnx)
package Tutorial3;
import java.util.Iterator;
public class MyLinkedList<E> implements Iterable<E> {
Elem<E> head;
Elem<E> tail;
public MyLinkedList() {
head = null;
tail = null;
}
public void add(E e) {
Elem<E> newElem = new Elem<E>(e);
if (head == null) {
tail.setNext(newElem);
head = newElem;
tail = newElem;
} else {
tail.setNext(newElem);
tail = newElem;
}
}
public void addToHead(E e) {
Elem<E> newElem = new Elem<E>(e);
newElem.setNext(head);
head = newElem;
}
public void addToTail(E e) {
add(e);
}
public void removeFirstValue() {
head = head.getNext();
}
public void removeLastValue() {
Elem<E> cursor;
cursor = head;
while (cursor.getNext() != tail) {
cursor = cursor.getNext();
}
tail = cursor;
tail.setNext(null);
}
public E get(int index) {
if ((index + 1) > size()) {
throw new IndexOutOfBoundsException("Index: " + index + " Size: " + size());
} else {
Elem<E> cursor;
cursor = head;
int i = 0;
if (i == index) {
return cursor.getE();
} else {
while (i != index) {
cursor = cursor.getNext();
i++;
}
return cursor.getE();
}
}
}
public int size() {
Elem<E> cursor;
cursor = head;
int size = 0;
while (cursor != null) {
size++;
cursor = cursor.getNext();
}
return size;
}
#Override
public Iterator<E> iterator() {
return new MyLinkedListIterator<E>();
}
private class MyLinkedListIterator<T> implements Iterator<T> {
private Elem elem = head;
#Override
public boolean hasNext() {
return elem.getNext() != null;
}
#Override
public T next() {
return elem.getNext().getE(); //here is mistake: can't return e
//required : T, Found: Object
}
}
}
package Tutorial3;
public class Elem<E> {
private E e;
private Elem<E> next;
public Elem(E e) {
this.e = e;
}
public Elem(E e, Elem<E> next) {
this.e = e;
this.next = next;
}
public E getE() {
return e;
}
public void setE(E e) {
this.e = e;
}
public Elem<E> getNext() {
return next;
}
public void setNext(Elem<E> next) {
this.next = next;
}
}
It should be
private class MyLinkedListIterator implements Iterator<E> {
private Elem<E> elem = head;
#Override
public boolean hasNext() {
return elem.getNext() != null;
}
#Override
public E next() {
return elem.getNext().getE();
}
}
Your MyLinkedListIterator type should inherit E from the outer MyLinkedList<E> type, instead of declaring its own element type T, and then you compounded that by using a raw Elem type instead of Elem<E>.

Why will my program not go into my while loop?

I'm working on a program that will take a name and number of a periodic element, store it in a tree and then print it out in different orders.
When I try and run my main class it asks for the name, but then it doesn't go into the while loop.
Here is my main class.
public class BinarySearchTree
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
String name;
int atomicNum;
BSTInterface<PeriodicElement> elements = new BSTree<PeriodicElement>();
PeriodicElement element;
int numElements;
String skip;
System.out.print("Element name (press Enter to end): ");
name = conIn.nextLine();
while (!name.equals(""));
{
System.out.print("Atomic Number: ");
atomicNum = conIn.nextInt();
skip = conIn.nextLine();
element = new PeriodicElement(name, atomicNum);
elements.add(element);
System.out.print("Element name (press ENTER TO END): ");
name = conIn.nextLine();
}
System.out.println();
System.out.println("Periodic Elements");
numElements = elements.reset(BSTree.INORDER);
for (int count = 1; count <= numElements; count++)
{
System.out.println(elements.getNext(BSTree.INORDER));
}
}
}
Here is my Binary Search Tree
public class BSTree <T extends Comparable<T>>
implements BSTInterface<T>
{
protected BSTNode<T> root;
boolean found;
protected LinkedUnbndQueue<T> inOrderQueue;
protected LinkedUnbndQueue<T> preOrderQueue;
protected LinkedUnbndQueue<T> postOrderQueue;
public BSTree()
{
root = null;
}
public boolean isEmpty()
{
return (root == null);
}
private int recSize(BSTNode<T> tree)
{
if(tree == null)
{
return 0;
}
else
{
return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
}
}
public int size()
{
int count = 0;
{
if(root != null)
{
LinkedStack<BSTNode<T>> hold = new LinkedStack<BSTNode<T>>();
BSTNode<T> currNode;
hold.push(root);
while(!hold.isEmpty())
{
currNode = hold.top();
hold.pop();
count++;
if(currNode.getLeft() != null)
{
hold.push(currNode.getLeft());
}
if(currNode.getRight() != null)
{
hold.push(currNode.getRight());
}
}
}
//System.out.println(count);
return count;
}
}
public boolean recContains(T element, BSTNode<T> tree)
{
if(tree == null)
{
return false;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recContains(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recContains(element, tree.getRight());
}
else
{
return true;
}
}
public boolean contains (T element)
{
//System.out.println("Tree contains: " + recContains(element, root));
return recContains(element, root);
}
public T recGet(T element, BSTNode<T> tree)
{
if(tree == null)
{
return null;
}
else if(element.compareTo(tree.getInfo()) < 0)
{
return recGet(element, tree.getLeft());
}
else if(element.compareTo(tree.getInfo()) > 0)
{
return recGet(element, tree.getRight());
}
else
{
return tree.getInfo();
}
}
public T get(T element)
{
//System.out.println(recGet(element, root));
return recGet(element, root);
}
public void add(T element)
{
root = recAdd(element, root);
}
private BSTNode<T> recAdd(T element, BSTNode<T> tree)
{
if(tree == null)
{
tree = new BSTNode<T>(element);
}
else if(element.compareTo(tree.getInfo()) <= 0)
{
tree.setLeft(recAdd(element, tree.getLeft()));
}
else
{
tree.setRight(recAdd(element, tree.getRight()));
}
return tree;
}
public boolean remove(T element)
{
root = recRemove(element, root);
return found;
}
private BSTNode<T> recRemove(T element, BSTNode<T> tree)
{
if(tree == null)
{
found = false;
}
else if (element.compareTo(tree.getInfo()) < 0)
{
tree.setLeft(recRemove(element, tree.getLeft()));
}
else if (element.compareTo(tree.getInfo()) > 0)
{
tree.setRight(recRemove(element, tree.getRight()));
}
else
{
tree = removeNode(tree);
found = true;
}
return tree;
}
private BSTNode<T> removeNode(BSTNode<T> tree)
{
T data;
if(tree.getLeft() == null)
{
return tree.getRight();
}
else if(tree.getRight() == null)
{
return tree.getLeft();
}
else
{
data = getPredecessor(tree.getLeft());
tree.setInfo(data);
tree.setLeft(recRemove(data, tree.getLeft()));
return tree;
}
}
private T getPredecessor(BSTNode<T> tree)
{
while (tree.getRight() != null)
{
tree = tree.getRight();
}
return tree.getInfo();
}
public int reset(int orderType)
{
int numNodes = size();
if(orderType == INORDER)
{
inOrderQueue = new LinkedUnbndQueue<T>(numNodes);
}
else
{
if(orderType == PREORDER)
{
preOrderQueue = new LinkedUnbndQueue<T>(numNodes);
preOrder(root);
}
if(orderType == POSTORDER)
{
postOrderQueue = new LinkedUnbndQueue<T>(numNodes);
postOrder(root);
}
}
return numNodes;
}
public T getNext(int orderType)
{
if(orderType == INORDER)
{
return inOrderQueue.dequeue();
}
else
{
if(orderType == PREORDER)
{
return preOrderQueue.dequeue();
}
else
{
if(orderType == POSTORDER)
{
return postOrderQueue.dequeue();
}
else
{
return null;
}
}
}
}
private void inOrder(BSTNode<T> tree)
{
if(tree != null)
{
inOrder(tree.getLeft());
inOrderQueue.enqueue(tree.getInfo());
inOrder(tree.getRight());
}
}
private void preOrder(BSTNode<T> tree)
{
if(tree != null)
{
preOrderQueue.enqueue(tree.getInfo());
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
}
private void postOrder(BSTNode<T> tree)
{
if(tree != null)
{
postOrder(tree.getLeft());
postOrder(tree.getRight());
postOrderQueue.enqueue(tree.getInfo());
}
}
}
Here is the Binary Search Tree Node class
public class BSTNode <T extends Comparable<T>>
{
protected T info;
protected BSTNode<T> left;
protected BSTNode<T> right;
public BSTNode(T info)
{
this.info = info;
left = null;
right = null;
}
public void setInfo(T info)
{
this.info = info;
}
public T getInfo()
{
return info;
}
public void setLeft(BSTNode<T> link)
{
left = link;
}
public void setRight(BSTNode<T> link)
{
right = link;
}
public BSTNode<T> getLeft()
{
return left;
}
public BSTNode<T> getRight()
{
return right;
}
}
Remove the semi-colon that is terminating the while statement
while (!name.equals(""));
^
Remove the semi colon after the while statment because a semi colon makes it end there while a { is the start if while something is true or not (!) and it should end as you obviously know with a }.

Categories