How would I reverse a queue without having a parameter. I'm trying to copy elements from another queue not in the method and reverse the elements. I have the algorithm but I don't know how to access original queue to copy.
public QueueInterface<T> reverseQueue() {
// TODO 8
Queue<T> a = new Queue<T>();
Stack<T> b = new Stack<T>();
while(!a.isEmpty()){
b.push(a.dequeue());
}
while(!b.isEmpty()){
a.enqueue(b.pop());
}
return a;
}
So I added this condition to add elements to a variable temp and run it through a recursive loop but it gives an error message that would be shown if the queue is empty, NoSuchElementException. Would it be easier to create another Queue instead of temp and place elements inside that or some other way.
public QueueInterface<T> reverseQueue() {
T temp = null;
Queue<T> a = new Queue<T>();
if (temp == null) {
temp = dequeue();
a.enqueue(temp);
reversed();
}
Related
I have tried to implement breadth first search but I believe I get stuck in a infinite for loop and I am not sure why. My method is below:
public ArrayList<T> performBreadthFirstSearchUndirectedNonWeighted(UndirectedNonWeightedGraph<T> graph, T startingVertex){
if (!graph.containsVertex(startingVertex)) {
throw new IllegalArgumentException("Vertex doesn't exist.");
}
T currentVertex;
ArrayList<T> traversalOrder = new ArrayList<T>();
ArrayList<T> visitedVertices = new ArrayList<T>();
LinkedList<T> queue = new LinkedList<T>();
visitedVertices.add(startingVertex);
queue.add(startingVertex);
while (queue.size() != 0) {
currentVertex = queue.poll();
traversalOrder.add(currentVertex);
Iterator<Vertex<T>> i = graph.getNeighbours(currentVertex).iterator();
while (i.hasNext()) {
Vertex<T> n = i.next();
if (!visitedVertices.contains(graph.returnVertex(n.getElement()))) {
visitedVertices.add(n.getElement());
queue.add(n.getElement());
}
}
}
return traversalOrder;
}
Any help is appreciated!
Thank you.
EDIT: Updated code still infinite loop.
Replace the line
if (!visitedVertices.contains(graph.returnVertex(n.getElement())))
by
if (!visitedVertices.contains(n.getElement()))
The method contains accept an Object as a parameter so it compiles fine but you have to give a object of type T. Normally if you are using an IDE, it should warn you on this line.
What is the type of Node T here? Does it implement equals() and hashcode() properly? Because the key checking of containing elements in the list will fail otherwise. Therefore, will always keep adding nodes to the Queue. You can do some simple debugging if the Queue is getting updated as expected.
.. I have to use a piece of code in java but I don't understand some parts of it.
The code uses methods (.isEmpty() etc. ) from a simple Queue i made in another document.
It is suppposed to investigate an array (which has linked lists in each address) and do some sort of processing with its values.
The problem is that i dont know what marked[s] = true; ,marked[t.v] = true; and parent[t.v] = k; are and how do they work as variables (?)
void BFS(int s)
{
Queue<Integer> Q = new Queue<Integer>();
marked[s] = true;
Q.put(s);
while (!Q.isEmpty())
{
k = Q.get();
for (Node t = adj[k]; t != null; t = t.next)
if (!marked[t.v]) {
marked[t.v] = true;
parent[t.v] = k;
Q.put(t.v);
}
}
}
}
edit: I wrote matrix instead of array, sorry.
marked[] parent and adj are all arrays.
t as you can see from the code, is a Node object. That node object will have a member variable called v. t.v therefore fetches the value of the variable v in the Node object t.
marked[t.v] finds the element in the array with index equal to t.v. e.g. if t.v is equal to 0, then you are fetching marked[0] which is the first element in the marked array.
When given an array of integers, I'm trying to change each element with the product of the integers before it.
For example, int[] array = {2,2,3,4}; is now: {2, 4, 12, 48};
I added each element to a LinkedList, and I'm trying to do this recursively.
This is what I have:
Node curr = list.getFirst();
product(curr);
public static void product(Node curr)
{
if(curr == null)
{
return;
}
else
{
int data = curr.getData() * curr.getNext().getData();
Node newNode = new Node(data);
curr.setNext(newNode);
// product(curr);
}
}
The first product works: {2,4}, but when I try to put in the recursion, I get a stackoverflow. Any suggestions??
Edit: So the reason that I'm either getting a stackoverflow or null pointer exception is because I'm updating the list, and then trying to get the next integer(but since there's only two elements in the list, there isn't a getNext()). I'm not sure how to fix this.
It looks like you were getting a bit tied up in the recursion. I modified your method to accept a Node along with the product from the previous iteration. At each step of the iteration I update the value in the already-existing List, so there is no need for using the new operator.
public static void product(Node curr, int value) {
if (curr == null) {
return;
}
else {
int data = value * curr.getData(); // compute current product
curr.setData(data); // update Node
product(curr.getNext(), data); // make recursive call
}
}
There are actually two issues with the code.
The recursion never ends, i.e. it is not actually moving to a smaller "subproblem" as the recursion is calling the same node again
and again.
After creating a new node and modifying the next we also need to connect the node "after" the next node otherwise the link will be
lost. Please check the below method which addresses both the issues.
Although I didn't do an excessive testing it is working for simple dataset.
Original List:
2->4->5->6->8->null
Multiplied List:
2->8->40->240->1920->null
public void product(Node curr) {
if (curr.getNext() == null) {
return;
} else {
int data = curr.getData() * curr.getNext().getData();
Node newNode = new Node();
newNode.setData(data);
Node nodeAfterNextNode = curr.getNext().getNext();
newNode.setNext(nodeAfterNextNode);
curr.setNext(newNode);
product(newNode);
}
}
It is because you call recursive method on the current node, so it is actually never move forward in the LinkedList. You can simply update the next node's data and call the recursive method on it. See the code below:
Node curr = list.getFirst();
product(curr);
public static void product(Node curr)
{
Node next = curr.getNext();
if(next == null)
{
return;
}
else
{
int data = curr.getData() * next.getData();
next.setData(data);
product(next);
}
}
I'm trying to iterate over an Object array. Using the next() method works so I'm guessing that my iterator class and constructors are working.
For some reason i'm not getting any output while the hasNext() method is running.
Iterator it = hej.iterator();
Object j = it.next();
System.out.println(j);
while(it.hasNext()){
Object i = it.next();
System.out.println(i + " ");
}
With "hej" being my Object array.
My code for the next(); and hasNext() methods are as follows:
public class StackIterator implements Iterator<Object>{
// fields
private int element = 0;
private final Object[] elements;
private final int max;
// constructor
public StackIterator(Object[] values, int maxIndex) {
elements = values;
max = maxIndex;
}
// methods
public boolean hasNext() {
return element < max;
}
public Object next() {
return elements[element++];
}
}
The file that constructs the Object Array and the Object Array depends on an interface:
public interface Stack {
int size();
boolean isEmpty();
void push(Object element);
Object pop();
Object peek();
Iterator<Object> iterator();
}
The methods are then explained in another file:
public class StackExample implements Stack {
// fields
int length = 0;
Object[] arr;
// constructor
public StackExample() {arr = new Object[length];}
// method returns size of object array
public int size() {
return arr.length;
}
// method checks if object is empty
public boolean isEmpty() {
boolean result = false;
if (arr.length == 0){
result = true;
}
return result;
}
// method for push
public void push(Object element) {
newBiggerObj();
arr[0] = element;
}
// returns the first object of the stack
public Object pop() {
Object[] temp = new Object[arr.length-1];
Object first = arr[0];
for (int i = 0; i<arr.length-1; i++){
temp[i] = arr[i+1];
}arr = temp;
return first;
}
// returns the object on top of stack
public Object peek() {
if (isEmpty()){
try{
throw new Exception("Stack empty, can't peek!");
}
catch(Exception e){
return e.getMessage();
}
}
else {
Object first = arr[0];
return first;
}
}
// method for push method
private void newBiggerObj(){
Object[] temp = new Object[arr.length+1];
for (int i = 0; i<arr.length; i++){
temp[i+1] = arr[i];
}
arr = temp;
}
public String toString(){
String str = "";
for (int i = 0; i < arr.length; i++){
str = str + arr[i] + " , ";
}return str;
}
public Iterator<Object> iterator() {
return new StackIterator(arr, length);
}
}
What bothers me is that the method Iterator is within itself returning an instance of the class Stack Iterator. Which i posted above. So my real problem seems to be that my fields are not being given any value, since I am not myself giving the any values within the constructor.
My main method in which I'm testing all of this is as follows:
public class Teststack {
public static void main(String[] args){
// new instane of class StackExample
StackExample hej = new StackExample();
// test for the different methods
System.out.println(hej.isEmpty());
System.out.println(hej.size());
hej.push(4);
hej.push("hej");
hej.push(6);
hej.push(5);
System.out.println(hej.size());
System.out.println(hej.peek());
System.out.println(hej.pop());
System.out.println(hej.toString());
System.out.println(hej.isEmpty());
System.out.println("Testing Iterator: ");
// test for iterator
Iterator it = hej.iterator();
Object j = it.next();
System.out.println(j);
while(it.hasNext()){
Object i = it.next();
System.out.println(i + " ");
}
}
}
In your StackExample class, I don't see the length variable being updated when elements are pushed or popped. Due to this, length will always be 0 and calls to it.hasNext() will always return false.
You don't need to pass the length as a separate argument. You can find the array's length in the StackIterator constructor and use it.
Also note that since you're creating a new array on every push and pop, the iterator returned by StackExample#iterator() will become stale after every push/pop since it will work on an old copy/state of the stack.
The problem is here:
public Iterator<Object> iterator() {
return new StackIterator(arr, length);
}
length field is never changed, so its value is always 0. You can change the code to this:
public Iterator<Object> iterator() {
return new StackIterator(arr, arr.length);
}
Also, before retrieving elements from the iterator, you should always call it.hasNext. The fact you did this:
Iterator it = hej.iterator();
Object j = it.next();
And worked was just pure luck.
Apart of this, I can sense you have a bad design on your stack implementation. Here are some hints to improve your code:
The inner array should be initialized with a default size different than 0. E.g. 10 (as done in java.util.ArrayList implementation).
You should avoid creating a new array when adding (push) or removing (pop) an element from your stack. Instead of this, you should use the length field to control how many elements are in your stack.
The value of the new size should be based on another formula rather than array.length + 1. For example, try using something like int newSize = array.length / 2 * 3;.
Resize the inner array only when necessary. When calling push, do it only if you precisely need to increase the size of the array. When calling pop, do it if the current length of the array (this is, array.length) is far greater than the value of length field of your class.
Never forget to update the value of length on push and pop methods.
Couple of issues:
You are calling Object j = it.next(); after creating iterator and then check for hasNext. You are incrementing the element index. Hence if you just have one element, you wont enter the while loop. In addition, if your custom datastructure is empty i.e. array has no elements then you are prone to ArrayIndexOutOfBoundException.
You will always iterate and print n-1 elements instead to n elements.
Once you iterated, then your pointer will always point to last element and never get resetted. So very next time you wont be able to iterate over your elements. Its a one time iterator.
Try not to call
Object j = it.next() statement, but just while cycle. Seems you have an array of just 1 element.
There are a number of problems with this code:
In the StackIterator constructor there is no bounds checking on maxIndex. Callers can pass in a number greater than values.length, less that 0, etc.
In the next method, there is no check of the end condition, either directly or by calling hasNext(). Callers can keep calling next() and see elements beyond max or even get an ArrayIndexOutOfBoundsException, when they should be getting a NoSuchElementException.
The Stack class never increments or decrements its length field when elements are pushed or popped.
The Stack class tracks the length separately from the array, even though it always resizes the array on every push or pop, but Java arrays already know their size. (But see the next item.)
The Stack class resizes the array on every push or pop, which is very inefficient. Typically classes like this only resize the array when necessary, allowing 'slack' space, to give amortized constant time performance (see ArrayList). If you do this, however, it is necessary to null out popped items to avoid unintentional object retention.
The Stack adds and removes elements at the beginning of the array. This is incredibly inefficient since it means a O(n) reshuffling must be done on every push or pop.
The peek() method takes into account the possibility that the Stack may be empty, but the pop() method does not. A pop() on an empty Stack will throw an ArrayIndexOutOfBoundsException.
Stack is not a generic class. It holds Object. Users of the Stack will have to cast the return values from peek() or pop(), and it isn't type safe. In your example, you show a stack that is a heterogeneous mixture of String and Integer. This is a very Java 1.2 way of doing things, and while it isn't necessarily wrong, you should consider parameterizing Stack.
private Node back isn't used yet, and enqueue (which was push) and dequeue (which was pop) haven't really been modified except for renaming some things. Again, this was originally a stack but I'm trying to modify it into a queue. I've done non-linked list queues and stacks before with ints, but with objects and linked lists I'm sort of lost.
public class DogQueue
{
private Node front = null;
private Node back = null;
private Node element = null;
private int counter = 0;
The above is just setting up variables.
private class Node //This sets up the Linked List
//Data Structure with nodes.
{
private Dog doggy;
private Node nextNode;
private Node firstNode;
Node(Dog newDog)
{
doggy = newDog;
}
}
Node stuff which I don't quite understand is above.
public void enqueue(Dog aDog) //This should enqueue
//an object of type Dog.
{
Node dogNode = new Node(aDog);
dogNode.nextNode = front;
counter++;
front = dogNode;
}
The above here is unmodified from the push method, just renamed.
public Dog dequeue() //This should output
//the first entry in the list.
{
Dog firstDog = front.doggy;
element = front.firstNode;
counter--;
return firstDog;
}
The above here is where I'm having the most trouble- currently it behaves like pop (getting and removing the last entered element in the list).
public boolean isFull() //Checks to see if List is Full.
{
return ( counter == 5 );
}
I set up the counter to just go up to 5 so I can debug isFull.
public boolean isEmpty() //Checks to see if List is empty
{
if ( counter == 0 )
{
return true;
} else {
return false;
}
}
This just says if counter is zero, then isEmpty is true (otherwise false).
}
I suck at data structures but I believe your enqueue and dequeue are still behaving like pop and push.
The front should point to the head of the queue and the tail one past the last valid object. So the tail should eventually point to null..
I think it should be something like this:
public void enqueue(Dog aDog)
{
Node dogNode = new Node(aDog);
counter++;
if (front == null)
front = back = dogNode;
else
{
back.nextNode = dogNode;
back = dogNode;
}
}
public Node dequeue()
{
if(front == null) return null;
Dog firstDog = front ;
front = front.nextNode;
counter--;
return firstDog;
}
Here's the main issue. Queues are FIFO (first in, first out), and Stacks are LIFO (last in, first out). For a queue, the first element you enqueue is the first one you receive, and the most recent element you push onto a stack is the first one you receive.
To that end, let's examine your code a bit.
public void enqueue(Dog aDog) { //This should enqueue an object of type Dog.
Node dogNode = new Node(aDog);
dogNode.nextNode = front;
counter++;
front = dogNode;
}
You're setting the next node of your new dog element to the front. You would have to go to the end of your queue, set your most recent node to be the new node, and the new node to be null. Using your code, it would look something like this:
public void enqueue(Dog aDog) {
if(front == null) {
front = new Node(aDog);
back = front; // back will move later
} else {
Node tmp = new Node(aDog);
tmp.setFirstNode(back);
back.setNextNode(tmp);
back = tmp;
}
}
public Dog dequeue() { //This should output the first entry in the list.
Dog firstDog = front.doggy;
element = front.firstNode;
counter--;
return firstDog;
}
At least, this does actually show the first thing in the queue. But it doesn't actually move the head pointer! Using your code, to do that, it would look something like this:
public Dog dequeue() {
if(head == null) {
return null;
} else {
Dog tmp = front.getDoggy()
front = front.getNextNode(); //move the front to point to the next location
front.getFirstNode().setNextNode(null); //sever the link to the first element
front.setFirstNode(null); //sever the link to the first element
return tmp;
}
}