I have the java code and been able to come up with a toString as shown below in the code:
public class CircularArrayQueue<T> implements QueueADT<T>
{
private final int DEFAULT_CAPACITY = 100;
private int front, rear, count;
private T[] queue;
//-----------------------------------------------------------------
// Creates an empty queue using the default capacity.
//-----------------------------------------------------------------
public CircularArrayQueue()
{
front = rear = count = 0;
queue = (T[]) (new Object[DEFAULT_CAPACITY]);
}
//-----------------------------------------------------------------
// Creates an empty queue using the specified capacity.
//-----------------------------------------------------------------
public CircularArrayQueue (int initialCapacity)
{
front = rear = count = 0;
queue = ( (T[])(new Object[initialCapacity]) );
}
//-----------------------------------------------------------------
// Adds the specified element to the rear of the queue, expanding
// the capacity of the queue array if necessary.
//-----------------------------------------------------------------
public void enqueue (T element)
{
if (size() == queue.length)
expandCapacity();
queue[rear] = element;
rear = (rear+1) % queue.length;
count++;
}
//-----------------------------------------------------------------
// Removes the element at the front of the queue and returns a
// reference to it. Throws an EmptyCollectionException if the
// queue is empty.
//-----------------------------------------------------------------
public T dequeue() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("queue");
T result = queue[front];
queue[front] = null;
front = (front+1) % queue.length;
count--;
return result;
}
//-----------------------------------------------------------------
// Returns a reference to the element at the front of the queue.
// The element is not removed from the queue. Throws an
// EmptyCollectionException if the queue is empty.
//-----------------------------------------------------------------
public T first() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("queue");
return queue[front];
}
//-----------------------------------------------------------------
// Returns true if this queue is empty and false otherwise.
//-----------------------------------------------------------------
public boolean isEmpty()
{
return (count == 0);
}
//-----------------------------------------------------------------
// Returns the number of elements currently in this queue.
//-----------------------------------------------------------------
public int size()
{
return count;
}
//-----------------------------------------------------------------
// Returns a string representation of this queue.
//-----------------------------------------------------------------
public String toString()
{
String result = "";
int scan = 0;
while(scan < count)
{
if(queue[scan]!=null)
{
result += queue[scan].toString()+"\n";
}
scan++;
}
return result;
}
//-----------------------------------------------------------------
// Creates a new array to store the contents of the queue with
// twice the capacity of the old one.
//-----------------------------------------------------------------
public void expandCapacity()
{
T[] larger = (T[])(new Object[queue.length *2]);
for(int scan=0; scan < count; scan++)
{
larger[scan] = queue[front];
front=(front+1) % queue.length;
}
front = 0;
rear = count;
queue = larger;
}
}
How can I modify my toString based on these output for my queue:
I want to Start with an initial String showing the number of cars
If the queue is empty, thenI will return the initial String.
If front is at, or ahead of, back
I want to add a line for each car from front to the end
then add lines for those from the start of the array to back-1
else I want to add a line for each car between front and back-1.
This is my current toString() :
public String toString()
{
String result = "";
for (int scan=0; scan < rear; scan++)
result = result + queue[scan].toString() + "\n";
return result;
}
You wrote the pseudo-code, a few if/else-if blocks do the rest.
public String toString()
{
String result = String.format("There are %d items in the queue.", count);
if (count == 0)
{
return result;
}
else if (front >= back)
{
for (int i = front; i < count; i++)
{
result += queue[i].toString() + "\n";
}
for (int i = 0; i < back; i++)
{
result += queue[i].toString() + "\n";
}
}
else
{
for (int i = front; i < back; i++)
{
result += queue[i].toString() + "\n";
}
}
return result;
}
Related
I have the following code where I have implemented a circular array. The problem comes when I try to display it. The display method works well until the array gets full and last goes back to 0. Therefore last and first are both 0 and the for loop doesn't execute.
public class PassengerQueue
{
private Passenger[] queueArray = new Passenger[TrainStation.WAITING_ROOM_CAPACITY];
private int first = 0;
private int last = 0;
private int maxStayInQueue = 0; //number of seconds that the passenger who stayed longest in the queue
private int maxLength = 0; //the maximum legth that was reached by the queue
private int currentSize = 0;
public void add(Passenger next)
{
//if the queue is not full - check for the circular queue
if (isFull()){
System.out.println("The queue is full");
}
else
{
queueArray[last] = next;
last = (last + 1) % queueArray.length;
currentSize++;
maxLength++;
}
}
public Passenger remove()
{
Passenger removedPassenger = null;
//if the queue array is not empty
//remove passenger
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
removedPassenger = queueArray[first];
queueArray[first] = null;
first = (first + 1) % queueArray.length;
currentSize--;
}
return removedPassenger;
}
public Boolean isEmpty()
{
return (currentSize == 0);
}
public Boolean isFull()
{
return (currentSize == queueArray.length);
}
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = first; i < last; i++)
{
queueArray[i].display();
}
}
}
Any help would be appreciated! Thank You
You can change the loop so it iterates from 0 to size. This also fixes the problem where last is less than first because items have been removed.
for(int i = 0; i < currentSize; i++)
{
queueArray[(first + i) % queueArray.length].display();
}
Just use the properties on the array itself to display:
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = 0; i < queueArray.length; i++)
{
queueArray[i].display();
}
}
}
When i run my code, i get nothing as my output. I suspect my code stops on this method:
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
I think it stops at the above method because this code:
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
only returns -1. If i remove the return -1; then Java thinks that there is an error because there is no return statment. I tried adding an else, but i still get the same error.
This is the whole code:
/** The interface for our List (Abstract Data Type) */
interface IList {
/** Adds the given value to the end of the list */
void append(char value);
/** Adds the given value to the beginning of the list */
void prepend(char value);
/** Deletes the container at the given position (a container holds a value) */
void deleteAt(int position);
/** Returns the number of values currently in our list */
int size();
/** Retrieves the value at the given position */
char getValueAt(int position);
/** Searches for the FIRST occurence of a given value in our list.
* If found, it returns the position of that value.
* If not found, it returns -1 */
int positionOf(char value);
}
/** Array implementation of our List */
class ListAsArray implements IList {
// initialize array to a size of 30 elements
// this will prevent the need to resize our array
char[] theArray = new char[30];
public void append(char value)
{
//Count until you find a place in the array that is empty, then insert
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
theArray[i] = value;
}
}
}
public void prepend(char value)
{
//Count until you find a empty value
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
//Once you find the empty value move everything over
for(int j = theArray.length; j != 0; j--)
{
theArray[i] = theArray[i + 1];
}
}
}
//Finally you want to actually add in the number in the first position
theArray[0] = value;
}
public void deleteAt(int position)
{
if (position >= 0)
{
for (int i = position; i < theArray.length; i++)
{
theArray[i] = theArray[i + 1];
}
}
}
public int size()
{
//Count until you find a place in the array that is empty, then return the number
int count = 0;
for (int i = 0; i < theArray.length; i ++)
{
if (theArray[i] == 0)
{
return count;
}
count ++;
}
return 0;
}
public char getValueAt(int position)
{
return theArray[position];
}
public int positionOf(char value)
{
//Search the list to find the value, if found return the position, if not, return -1
for (int i = 0; i < size(); i ++)
{
if (theArray[i] == value)
{
return i;
}
}
return -1;
}
}
/** Singly Linked List implementation of our List */
class ListAsLinkedList implements IList {
//Point to first node and second node
private Node head;
private Node tail;
//Constructor sets head and tail to null
public void LinkedList()
{
head = null;
tail = null;
}
public void append(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
//Set new node to be after current end
tail.setNext(temp);
//Set as new tail
tail = temp;
}
}
public void prepend(char value)
{
//Wrap the data in a node
Node temp = new Node(value);
//Make this the first node if no other nodes
if (tail == null)
{
//Set tail to new node
tail = temp;
//Set head to new node
head = temp;
}
else
{
temp.next = head;
head = temp;
}
}
public void deleteAt(int position)
{
//Make the head node the next node if its the first one
if(position == 0)
{
head=head.next;
}
//If that wasn't the case...
Node current = head;
for(int i = 0; i < position-1; i++)
{
current = current.next;
}
current.next = current.next.next;
if(current.getNext() == null)
{
tail = current;
}
}
public int size()
{
Node temp = head;
for (int i = 0; i != 103; i++)
{
if (temp == tail)
{
return i;
}
}
return 0;
}
public char getValueAt(int position)
{
Node temp=head;
for(int i=0; i < position; i++)
{
temp=temp.next;
}
return temp.data;
}
public int positionOf(char value)
{
//Start at the beginning
int position = 0;
Node current = head;
//Look until we find target data
while (current.getData() != value)
{
//Move to next node
current = current.getNext();
//Increment position
position++;
}
//return position found
return position;
}
}
/** A singly linked list node for our singly linked list */
class Node {
//The node data and link to next node
public char data;
public Node next;
//Constructor
public Node(char data)
{
this.data = data;
this.next = null;
}
//Accessor
public char getData()
{
return data;
}
//Accessor
public Node getNext()
{
return next;
}
//Mutator
public void setData(char data)
{
this.data = data;
}
//Mutator
public void setNext(Node next)
{
this.next = next;
}
}
This is main:
/** contains our entry point */
public class Main {
/** entry point - DO NOT CHANGE the pre-existing code below */
public static void main(String[] args) {
int[] numbers = {105,116,112,115,65,58,47,47,116,105,110,121,88,117,114,108,46,99,111,109,47};
int[] numbers2 = {97,59,111,53,33,111,106,42,50};
int[] numbers3 = {116,104,32,111,116,32,111,71};
/// List as an Array
IList array = new ListAsArray();
// add values
for(int num : numbers) {
array.append((char)num);
}
for(int num : numbers3) {
array.prepend((char)num);
}
// delete some values
int position;
position = array.positionOf((char)105);
array.deleteAt(position);
position = array.positionOf((char)65);
array.deleteAt(position);
position = array.positionOf((char)88);
array.deleteAt(position);
// print em
position = 0;
while (position < array.size()) {
System.out.print(array.getValueAt(position));
position++;
}
/// List as a Linked List
IList linkedList = new ListAsLinkedList();
// add values
for(int num : numbers2) {
linkedList.append((char)num);
}
linkedList.prepend((char)55);
linkedList.prepend((char)121);
// delete some values
position = linkedList.positionOf((char)59);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)33);
linkedList.deleteAt(position);
position = linkedList.positionOf((char)42);
linkedList.deleteAt(position);
// print em
position = 0;
while (position < linkedList.size()) {
System.out.print(linkedList.getValueAt(position));
position++;
}
System.out.println();
// ???
}
}
It should be outputting a link pertaining to the next part of my assignment.
The size() method always returns 0 according to your input.
size() method as per your code doesn't give you the length of the array to iterate over. Therefore you should use array length i.e theArray.length in positionOf() method's for loop instead of size() method.
I am implementing a Generic Queue using Linked list. I have the following methods: enqueue, dequeue and peek. I need help with writing a method that will find the minimum value in the queue and throw an exception if the queue is empty.
The code I have so far is:
class Queue <T>
{
private Node front, rear; //begin and end nodes
private int size; // number of items
//nested class to define node
private class Node
{
T item;
Node next;
}
//Zero argument constructor
public Queue()
{
front = null;
rear = null;
size = 0;
}
public boolean isEmpty()
{
return (size == 0);
}
//peek method
public T peek(){
T item = front.item;
return item;
}
//Remove item from the beginning of the list.
public T dequeue()
{
T item = front.item;
front = front.next;
if (isEmpty())
{
rear = null;
}
size--;
return item;
}
//Add T to the end of the list.
public void enqueue(T item)
{
Node oldRear = rear;
rear = new Node();
rear.item = item;
rear.next = null;
if (isEmpty())
{
front = rear;
}
else
{
oldRear.next = rear;
}
size++;
}
public int size()
{
return size;
}
//finds the maximum and minimum in the list
//assumes that head pointer is defined elsewhere
public static void main (String a[])
{
Queue <Integer> q = new Queue<Integer>();
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.enqueue(60);
q.enqueue(70);
System.out.println("Delete an item from queue: " + q.dequeue());
System.out.println("Size of the queue: " + q.size());
System.out.println("Size of the queue: " + q.peek());
}
}
The below method should find the min value and an exception if Queue is empty
I am throwing a custom "QueueEmptyException"
public Integer findMin(Queue q){
if ( q.size == 0 )
throw new QueueEmptyException();
Integer min = q.front.item;
While (q.front.next != null) {
if ( min > q.front.next.item ) {
min = q.front.next.item
q.front = q.front.next;
}
return min;
I want to create a linked list then populate it with 1-100. After that I print out all the even numbers without actually removing the odd numbers from the list, then print out the even numbers again, but double them. After these things, I remove the odd numbers from the linked list and print out the list. The last step that I have mentioned is where I am hung up. Everything else works fine, just my remove method removes all the odd numbers except 1. In my main method I use an if statement that says if the number contained in the node % 2 equals zero, remove the node. It works for every node except the first one. Thank you guys for any help you can give me. My code follows.
import java.util.*;
/*
* My ListNode class
*/
class ListNode<Integer> {
private Integer item;
private ListNode<Integer> next;
public ListNode(Integer item) {
this.item = item;
next = null;
}
public ListNode(Integer item, ListNode<Integer> next) {
this.item = item;
this.next = next;
}
public Integer getItem() {
return item;
}
public ListNode<Integer> getNext() {
return next;
}
public void setItem(Integer item) {
this.item = item;
}
public void setNext(ListNode<Integer> next) {
this.next = next;
}
}
/*
* My LinkedList class
*/
class LinkedList<Integer> {
public ListNode<Integer> front;
public LinkedList() {
front = null;
}
public boolean isEmpty() {
return front == null;
}
public boolean contains(int target) {
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
if (node.getItem().equals(target)) {
return true;
}
}
return false;
}
public int size() {
int count = 0;
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
count++;
}
return count;
}
public String toString() {
String result = "( ";
for (ListNode<Integer> node = front;
node != null;
node = node.getNext()) {
result += node.getItem() + " ";
}
return result + ")";
}
public Integer get(int index) {
ListNode<Integer> node = front;
for (int i = 0; i < index; i++) {
node = node.getNext();
}
return node.getItem();
}
public void set(int index, Integer target) {
ListNode<Integer> node = front;
for (int i = 0; i < index; i++) {
node = node.getNext();
}
node.setItem(target);
}
public void add(int index, int target) {
if (isEmpty()) {
front = new ListNode(target);
} else {
ListNode last = front;
while (last.getNext() != null) {
last = last.getNext();
}
last.setNext(new ListNode(target));
}
}
public Integer remove(int index) {
ListNode<Integer> node = front;
ListNode<Integer> prev = front;
for (int i = 0; i < index; i++) {
prev = node;
node = node.getNext();
}
prev.setNext(node.getNext());
return node.getItem();
}
}
public class LinkedListTest {
//interface Removal {
//Integer remove (Integer item);
//}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
System.out.println(list);
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This adds the numbers 1 through 100 to a LinkedList
*/
for (int i = 1; i <= 100; i++)
list.add(0, i);
System.out.println(list);
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This prints out only even numbers by excluding indexes that are even,
* because all the even numbers are held in the odd numbered indexes, thus
* index 0 is 1 but index 1 is 2, index 3 is 4
*/
for (int i = 0; i < list.size(); i++)
if (i % 2 == 1) {
System.out.print(list.get(i) + " ");
}
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
/*
* This doubles even numbers
*/
for (int i = 0; i < list.size(); i++)
if (i % 2 == 1) {
int result = list.get(i) * 2;
System.out.print(result + " ");
}
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
for (int i = 0; i < list.size(); i++)
if (list.get(i) % 2 == 1) {
list.remove(i);
}
System.out.print(list);
System.out.println();
System.out.println("The list size is " + list.size());
System.out.println();
/*
* These contain methods only work for the first list created
*/
System.out.println("Does the list contain 32? " + list.contains(32));
System.out.println("Does the list contain 33? " + list.contains(33));
}
}
Your remove method doesn't actually work when value of index is 0.. Because both your node and prev are initialized to front and the loop is not being executed because the i<index condition is false. So you have to add another condition for the case of index=0
Adding these lines at the starting of your remove method solves the problem..
if(index==0){
ListNode<integer>temp=front;
front=front.getNext();
return temp.getItem();
}
hope it helped...
i believe the error is caused by incorrect adding to the queue and there might be other errors but i think it is something here
public void add(E data)
{
if(size == 0)
{
size++;
front = new ListNode(data,null);
}
else
{
size++;
ListNode <E> temp = end;
temp.setNext(null);
temp = temp.getNext();
temp.setData(data);
end = temp;
}
}
if you need the rest of the code to find the error here is the full class
import java.util.*;
public class Queue<E>
{
private ListNode <E> front;
private ListNode <E> end;
private int size;
public Queue()
{
front = null;
end = null;
size = 0;
}
public E peek()
{
return front.getData();
}
public E remove()
{
if(size == 0){return null;}
else
{
ListNode <E> temp = front;
front = temp.getNext();
size--;
return temp.getData();
}
}
public void add(E data)
{
if(size == 0)
{
size++;
front = new ListNode(data,null);
}
else
{
size++;
ListNode <E> temp = end;
temp.setNext(null);
temp = temp.getNext();
temp.setData(data);
end = temp;
}
}
public boolean isEmpty()
{
if (size == 0)
return true;
else
return false;
}
// [data, data, data, data]
public String toString()
{
String s ="";
ListNode <E> temp = front;
while(temp.getNext()!= null)
{
s+=temp.getData() + ", ";
}
return s;
}
public int size()
{
return size;
}
}
and here is the node i'm using
public class ListNode<E>
{
private E data;
private ListNode<E> next;
/**
* Constructs a ListNode with a specified data and next
* #param d the data for the node
* #param n the next reference
*/
public ListNode(E d, ListNode<E> n)
{
data = d;
n = next;
}
/**
* returns the data from the node
* #return the data field
*/
public E getData() {return data;}
/**
* sets the data for the node
* #param d the new data field
*/
public void setData(E d) {data = d;}
/**
* gets the next reference of the node
* #return the next reference
*/
public ListNode<E> getNext() { return next; }
/**
* sets the next reference for the node
* #param n the new next reference
*/
public void setNext(ListNode<E> n) { next = n;}
}
and this is what i am using to test it
public class QueueTester
{
public static void main (String args[])
{
Queue<Integer> queue = new Queue<Integer>();
for (int k = 1; k <= 100; k++) // add 1 to 100
queue.add(k);
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
for (int k = 1; k <= 50; k++) // remove 1 to 50, contents 51 to 100
{
int number = queue.remove();
}
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
for (int k = 200; k <= 500; k+=10) // add tens 200 to 500 (after 51 to 100)
queue.add(k);
System.out.println ("Size: " + queue.size());
System.out.println(queue + "\n");
while (!queue.isEmpty()) // prints contents (should be 51 to 100, then 200 to 500 tens)
{
System.out.print(queue.remove() + " ");
}
System.out.println("\n");
System.out.println ("Size: " + queue.size());
System.out.println(queue); // empty
System.out.println ("Remove from empty queue: " + queue.remove() + "\n") ;
}
}
try this..
if(size == 0)
{
front = new ListNode(data,null);
end = first;
size++;
}
else
{
ListNode <E> temp = new ListNode(data);
end.setNext(temp);
end = end.getNext();
size++;
}
Your add method is not implemented correctly and will always just change the front.
When you call eventually call remove()
public E remove()
{
if(size == 0){return null;}
else
{
ListNode <E> temp = front;
front = temp.getNext();
size--;
return temp.getData();
}
}
since size == 0, you will return null. You then try to dereference null into an int
int number = queue.remove();
This will throw a NullPointerException.
Review your logic, if you add something to the list, you should probably increment the size.
Also, note that in your add() method
ListNode <E> temp = end;
temp.setNext(null);
will also fail since end is originally null.