Time out issue in java - 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));
}
}

Related

LinkedQueue next value doesn't work as indeed

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;
}
}

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>.

what is wrong with this deque implementation

I want to write implementation of Deque
I have written code below but unfortunately I have a problem with it
when I use addFirst and addLast or even removeFirst every thing is ok
but when I use removelast the programs throws NullPointerException
I dont know what is the problem exactly so I got really confused
Can Anyone plaese Help me??
Thanks in advance for your attention
Node Class::
public class Node<E>{
E element;
Node<E> prev , next;
public Node(E element, Node<E> prev, Node<E> next) {
this.element = element;
this.prev = prev;
this.next = next;
}
public Node() {
this(null, null, null);
}
public void setNext(Node next)
{
this.next = next;
}
public void setPrev(Node prev)
{
this.prev = prev;
}
public Node getNext()
{
return next;
}
public Node getPrev()
{
return prev;
}
}
here is Deque Interface::
public interface DQ<E> {
public int size();
public boolean isEmpty();
public E getFirst();
public E getLast();
public void addFirst (E element);
public void addLast (E element);
public E removeFirst();
public E removeLast();
}
and finally here is MyDQ Class which implements DQ class::
public class MyDQ<E> implements DQ<E>{
Node<E> head , tail;
int size = 0;
#Override
public int size() {
return size;
}
#Override
public boolean isEmpty() {
return size == 0;
}
#Override
public E getFirst() {
if(head == null)
return null;
return head.element;
}
#Override
public E getLast() {
if(head == null)
return null;
return tail.element;
}
#Override
public void addFirst(E element) {
Node<E> n = new Node<>(element, null, null);
if(head == null)
head = tail = n;
else
{
head.setPrev(n);
n.setNext(head);
head = n;
}
size++;
}
#Override
public void addLast(E element) {
Node<E> n = new Node<>(element, null, null);
if(head == null)
head = tail = n;
else
{
tail.setNext(n);
n.setPrev(head);
tail = n;
}
size++;
}
#Override
public E removeFirst() {
if(head == null)
return null;
Node<E> n = head;
head = head.getNext();
head.setPrev(null);
n.setNext(null);
size --;
return n.element;
}
#Override
public E removeLast() {
if(head == null)
return null;
Node<E> n = tail;
tail = tail.getPrev();
tail.setNext(null);
n.setPrev(null);
size --;
return n.element;
}
}
I created a simple Person object to use:
public class Person {
String name;
Integer age;
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
}
I tested this using the following unit test:
#Test
public void testOneElementDeque() {
MyDQ<Person> deq = new MyDQ<>();
Person p1 = new Person("John", 12);
Person p2 = new Person("Eric", 45);
deq.addLast(p1);
assertEquals(p1, deq.getLast());
assertEquals(p1, deq.getFirst());
deq.removeLast();
}
This throws a null pointer at this line(line 78):
tail.setNext(null);
By this point in the call tail has been set to null by this line:
tail = tail.getPrev();
To correct this I rewrote the implementaion to null check tail at this point:
public E removeLast() {
if(tail == null)
return null;
Node<E> n = tail;
tail = tail.getPrev();
if(tail != null)
tail.setNext(null);
n.setPrev(null);
size --;
return n.element;
}

Categories