Generics in Java (Queue) - java

i implemented a Stack Class.
Now, i want to create a Queue based on that stack. Like this :
public class Queue<E> {
private Stack<E> next;
private Stack<E> next2;
public E first() {
}
public Queue<E> enqueue(E e) {
}
public Queue<E> dequeue() {
}
public boolean isEmpty() {
if (this.next == null) {
return true;
}
if (Stack.isEmpty(next)) {
return true;
}
return false;
}
}
I don't know where to start. How can i solve this problem? My first ideas was to use the method "reverse" in Stack. But i'm not sure.

There are 2 ways to do this. First one is to push at the end of stack using your function reverse. Like this
public class Queue<E> {
private Stack<E> next;
public E front() {
return (E) Stack.<E>top(next);
}
public Queue<E> enqueue(E e) {
Stack<E> nextNew = Stack.reverse(next);
nextNew = Stack.push(nextNew, e);
nextNew = Stack.reverse(nextNew);
Queue<E> q = new Queue<E>();
q.next = nextNew;
return q;
}
public Queue<E> dequeue() {
Stack<E> nextNew = Stack.pop(next);
Queue<E> q = new Queue<E>();
q.next = nextNew;
return q;
}
public boolean isEmpty() {
if (this.next == null) {
return true;
}
if (Stack.isEmpty(next)) {
return true;
}
return false;
}
}

I think it's slickest with recursion:
public class Queue<E> {
private Stack<E> stack;
public Queue(Stack stack) {
this.stack = stack;
}
public E front() {
return Stack.top(stack);
}
public Queue<E> enqueue(E newValue) {
if (Stack.top(stack) == null) {
return new Queue(Stack.push(Stack.create(), newValue));
}
return new Queue<>(Stack.push(new Queue(Stack.pop(stack)).enqueue(newValue).stack, Stack.top(stack)));
}
public Queue<E> dequeue() {
return new Queue<>(Stack.pop(stack));
}
public String toString() {
return "Q: " + stack.toString();
}
}
Note that there's no reversing required.
I thought some of the code in the Stack class was a little unclear with the "a" parameters and extra variables, so I refactored it a bit and stripped out everything that wasn't used. I also added a toString() which traverses the stack recursively:
public class Stack<E> {
private final E value;
private final Stack<E> next;
private Stack(E value, Stack<E> next) {
this.value = value;
this.next = next;
}
public static <E> Stack<E> create() {
return new Stack<>(null, null);
}
public static <E> Stack<E> push(Stack<E> stack, E newValue) {
return new Stack<E>(newValue, stack);
}
public static <E> Stack<E> pop(Stack<E> stack) {
if (stack == null) {
return new Stack<E>(null, null);
} else if (stack.value == null) {
return new Stack<>(null, null);
} else if (stack.next == null) {
return new Stack<E>(null, null);
} else {
return stack.next;
}
}
public static <E> E top(Stack<E> stack) {
if (stack == null) {
return null;
} else if (stack.value == null) {
return null;
} else {
return stack.value;
}
}
public String toString() {
if (Stack.top(next) == null) {
return (value != null ? value.toString() : "Null");
}
return (value != null ? value.toString() : "Null") + " " + next.toString();
}
}
And a little testing class. To show the difference between the stack and the queue, it loads up a stack first, then passes it to a Queue and adds a few more elements, then pulls a few off the front:
public class QueueWithStackMain {
public static void main(String[] args) {
Stack<String> stack = Stack.create();
stack = Stack.push(stack, "1");
System.out.println(stack.toString());
stack = Stack.push(stack, "2");
System.out.println(stack.toString());
stack = Stack.push(stack, "3");
System.out.println(stack.toString());
Queue<String> queue = new Queue<>(stack);
System.out.println(queue.toString());
queue = queue.enqueue("4");
System.out.println(queue.toString());
queue = queue.enqueue("5");
System.out.println(queue.toString() + " -> " + queue.front());
queue = queue.dequeue();
System.out.println(queue.toString() + " -> " + queue.front());
}
}

Related

Reverse a stack using only queue in Java?

I need to loop through the stack until it is empty, adding each element to the queue. Then do the opposite. Loop through the queue until it is empty, adding each element back onto the stack
public class Q1 {
public static void reverseStack(Stack st){
}
}
Here is my test:
public class Q1Test {
#Test
public void testQ1() {
Stack st = new Stack(5);
st.push("A");
st.push("B");
Q1.reverseStack(st);
assertEquals("A",(String) st.top());
}
}
I have been trying to do the Q1 code and never get it to succeed and always end up fail. Can anyone implement a methods as said above to make the Q1 test succeed please?
Here is a working example:
Q1.java
import java.util.ArrayList;
import java.util.List;
public class Q1 {
private List<String> list;
public Q1() {
list = new ArrayList<String>();
}
public String pop_front() {
if (!list.isEmpty()) {
String front = list.get(0);
for (int i = 0; i < list.size()-1; i++) {
list.set(i, list.get(i+1));
}
list.remove(list.size()-1);
return front;
} else {
return null;
}
}
public void push_back(String obj) {
list.add(obj);
}
public String front() {
if (!list.isEmpty()) {
return list.get(0);
} else {
return null;
}
}
public boolean isEmpty() {
return list.isEmpty();
}
public static void reverseStack(Stack stack) {
Q1 queue = new Q1();
while (!stack.isEmpty()) {
queue.push_back(stack.pop());
}
while (!queue.isEmpty()) {
stack.push(queue.pop_front());
}
}
}
A Stack class:
Stack.java
package com.dub;
import java.util.ArrayList;
import java.util.List;
public class Stack {
private List<String> list;
public Stack() {
list = new ArrayList<String>();
}
public String pop() {
if (!list.isEmpty()) {
String top = list.get(list.size()-1);
list.remove(list.size()-1);
return top;
} else {
return null;
}
}
public void push(String obj) {
list.add(obj);
}
public String top() {
if (!list.isEmpty()) {
return list.get(list.size()-1);
} else {
return null;
}
}
public boolean isEmpty() {
return list.isEmpty();
}
}
and now the test method:
public static void main(String[] args) {
Stack stack = new Stack();
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println("top: " + stack.top());
Q1.reverseStack(stack);
System.out.println("top: " + stack.top());
}
It prints as expected:
top: C
top: A

Properly Writing Object Oriented Code in java for a stack

I'm trying to write code in a way that it is object oriented. In this particular case I want to keep track of the minimum value of my stack in O(1) time. I know how to do it, the idea of it, well my idea of it, which is to have another stack that keeps track of the minimum value for every push and pop.
I've nested every class inside of the program class which is called minStack, which doesn't seem like the right thing to do however when I create a instance of minStack and call its variables it works out fine for a regular stack. I created a class that extends a Stack called StackWithMin but I don't know how to call its values. Should I create a new instance of a StackWithMin? If so how would i do it? I did it at the end of the code above the main function, but peek() always returns null
class minStack {
public class Stack {
Node top;
Object min = null;
Object pop() {
if(top != null) {
Object item = top.getData();
top = top.getNext();
return item;
}
return null;
}
void push(Object item) {
if(min == null) {
min = item;
}
if((int)item < (int)min) {
min = item;
}
Node pushed = new Node(item, top);
top = pushed;
}
Object peek() {
if(top == null) {
//System.out.println("Its null or stack is empty");
return null;
}
return top.getData();
}
Object minimumValue() {
if(min == null) {
return null;
}
return (int)min;
}
}
public class Node {
Object data;
Node next;
public Node(Object data) {
this.data = data;
this.next = null;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public void setNext(Node n) {
next = n;
}
public Node getNext() {
return next;
}
public void setData(Object d) {
data = d;
}
public Object getData() {
return data;
}
}
public class StackWithMin extends Stack {
Stack s2;
public StackWithMin() {
s2 = new Stack();
}
public void push(Object value) {
if((int)value <= (int)min()) {
s2.push(value);
}
super.push(value);
}
public Object pop() {
Object value = super.pop();
if((int)value == (int)min()) {
s2.pop();
}
return value;
}
public Object min() {
if(s2.top == null) {
return null;
}
else {
return s2.peek();
}
}
}
Stack testStack = new Stack();
StackWithMin stackMin = new StackWithMin();
public static void main(String[] args) {
minStack mStack = new minStack();
//StackWithMin stackMin = new StackWithMin();
mStack.testStack.push(3);
mStack.testStack.push(5);
mStack.testStack.push(2);
mStack.stackMin.push(2);
mStack.stackMin.push(4);
mStack.stackMin.push(1);
System.out.println(mStack.testStack.peek());
System.out.println(mStack.stackMin.peek());
mStack.testStack.pop();
}
}
I would suggest to create generic interface Stack like this one
interface Stack<T> {
void push(T item);
T pop();
T peek();
}
Generics add stability to your code by making more of your bugs
detectable at compile time.
See more about generics here.
Then implement this interface in a common way. All implementation details will be hidden inside of this class (your Node class for example). Here is the code (it is just to show the idea, if you want to use it you need to improve it with exception handling for example). Note that class Node is now also generic.
class SimpleStack<T> implements Stack<T> {
private class Node<T> { ... }
private Node<T> root = null;
public void push(T item) {
if (root == null) {
root = new Node<T>(item);
} else {
Node<T> node = new Node<T>(item, root);
root = node;
}
}
public T pop() {
if (root != null) {
T data = root.getData();
root = root.getNext();
return data;
} else {
return null;
}
}
public T peek() {
if (root != null) {
return root.getData();
} else {
return null;
}
}
}
Now we get to the part with stored minimum value. We can extend our SimpleStack class and add field with another SimpleStack. However I think this is better to make another implementation of the Stack and store two stacks for values and for minimums. The example is below. I have generalize the class that now uses Comparator to compare object, so you can use any other object types.
class StackWithComparator<T> implements Stack<T> {
private Comparator<T> comparator;
private SimpleStack<T> mins = new SimpleStack<>();
private SimpleStack<T> data = new SimpleStack<>();
public StackWithComparator(Comparator<T> comparator) {
this.comparator = comparator;
}
public void push(T item) {
data.push(item);
if (mins.peek() == null || comparator.compare(mins.peek(), item) >= 0) {
mins.push(item);
} else {
mins.push(mins.peek());
}
}
public T pop() {
mins.pop();
return data.pop();
}
public T peek() {
return data.peek();
}
public T min() {
return mins.peek();
}
}
Now you can use both implementations like so
SimpleStack<Integer> s1 = new SimpleStack<>();
s1.push(1);
s1.push(2);
s1.push(3);
System.out.println(s1.pop()); // print 3
System.out.println(s1.pop()); // print 2
System.out.println(s1.pop()); // print 1
StackWithComparator<Integer> s2 = new StackWithComparator<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
});
s2.push(1);
s2.push(2);
s2.push(3);
s2.push(0);
s2.push(4);
System.out.println(s2.min() + " " + s2.pop()); // print 0 4
System.out.println(s2.min() + " " + s2.pop()); // print 0 0
System.out.println(s2.min() + " " + s2.pop()); // print 1 3
System.out.println(s2.min() + " " + s2.pop()); // print 1 2
System.out.println(s2.min() + " " + s2.pop()); // print 1 1

Issue returning dequeued value from ImmutableQueue

I am implementing an immutable queue using the following code :
import java.util.NoSuchElementException;
import java.util.Queue;
public class ImmutableQueue<E> {
//Two stacks are used. One is to add items to the queue(enqueue) and
//other is to remove them(dequeue)
E returnedItem;
private ImmutableQueue(ReversableStack<E> order, ReversableStack<E> reverse) {
this.order = order;
this.reverse = reverse;
}
//initially both stacks are empty
public ImmutableQueue() {
this.order = ReversableStack.emptyStack();
this.reverse = ReversableStack.emptyStack();
}
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
public ImmutableQueue<E> dequeue() {
if (this.isEmpty())
throw new NoSuchElementException();
if (!this.reverse.isEmpty()) {
returnedItem = this.reverse.head;
return new ImmutableQueue<E>(this.order, this.reverse.tail);
} else {
returnedItem = this.reverse.head;
return new ImmutableQueue<E>(ReversableStack.emptyStack(),
this.order.getReverseStack().tail);
}
}
private static class ReversableStack<E> {
private E head; //top of original stack
private ReversableStack<E> tail; //top of reversed stack
private int size;
//initializing stack parameters
private ReversableStack(E obj, ReversableStack<E> tail) {
this.head = obj;
this.tail = tail;
this.size = tail.size + 1;
}
//returns a new empty stack
public static ReversableStack emptyStack() {
return new ReversableStack();
}
private ReversableStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
//Reverses the original stack
public ReversableStack<E> getReverseStack() {
ReversableStack<E> stack = new ReversableStack<E>();
ReversableStack<E> tail = this;
while (!tail.isEmpty()) {
stack = stack.push(tail.head);
tail = tail.tail;
}
return stack;
}
public boolean isEmpty() {
return this.size == 0;
}
public ReversableStack<E> push(E obj) {
return new ReversableStack<E>(obj, this);
}
}
private ReversableStack<E> order;
private ReversableStack<E> reverse;
private void normaliseQueue() {
this.reverse = this.order.getReverseStack();
this.order = ReversableStack.emptyStack();
}
public E peek() {
if (this.isEmpty())
throw new NoSuchElementException();
if (this.reverse.isEmpty())
normaliseQueue();
return this.reverse.head;
}
public boolean isEmpty() {
return size() == 0;
}
//returns the number of items currently in the queue
public int size() {
return this.order.size + this.reverse.size;
}
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue=newQueue.enqueue(5);
newQueue=newQueue.enqueue(10);
newQueue=newQueue.enqueue(15);
//newQueue = newQueue.dequeue();
//System.out.print(newQueue);
int x = newQueue.peek();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
}
The dequeue function does not seem to return the removed item, it only removes it. This the commented line by the way. How do I access the removed item ?
I have created a variable of type E in the main class. Now how do I access it in main and get the dequed value ?
Thanks

Junit testing stack pop

I am trying to use Junit it test if my stack is working properly. I am getting the output:
testPopEmptyStack(StackTesting.TestJunitStack): null
false
However I expect to get an output true because in my stack class. If pop() a stack that has no nodes in it, I wanted it to throw new EmptyStackException().
stack class:
public class Stack {
Node top;
int count = 0;
ArrayList<Node> stack = new ArrayList<Node>();
public boolean checkEmpty() {
if (count == 0) {
return false;
}
else {
return true;
}
}
public Node getTop() {
if (count > 0) {
return top;
}
else {
return null;
}
}
public void pop() {
if (count > 0) {
stack.remove(0);
count--;
}
else {
throw new EmptyStackException();
}
}
public void push(int data) {
Node node = new Node(data);
stack.add(node);
count++;
}
public int size() {
return count;
}
}
TestJunitStack.java:
public class TestJunitStack extends TestCase{
static Stack emptystack = new Stack();
#Test(expected = EmptyStackException.class)
public void testPopEmptyStack() {
emptystack.pop();
}
}
TestRunnerStack.java:
public class TestRunnerStack {
public void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunitStack.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
EDIT
static removed from testPopEmptyStack
Remove static from here
public static void testPopEmptyStack() {
...

Creating queue from two stacks

Can someone explain what am I doing wrong here ?
I am trying to create a queue from two stacks as per a book exercise. I get error "Stack Underflow" from the peek function. But everything seems right to me :P Please explain. Thanks!
//Program to implement Queue using two Stacks.
import java.util.NoSuchElementException;
public class Ex3_5_Stack {
int N;
int countOfNodes=0;
private Node first;
class Node {
private int item;
private Node next;
}
public Ex3_5_Stack() {
first=null;
N=0;
}
public int size() {
return N;
}
public boolean isEmpty() {
return first==null;
}
public void push(int item){
if (this.countOfNodes>=3) {
Ex3_5_Stack stack = new Ex3_5_Stack();
stack.first.item=item;
N++;
} else {
Node oldfirst = first;
first = new Node();
first.item=item;
first.next=oldfirst;
N++;
}
}
public int pop() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
int item = first.item;
first=first.next;
return item;
}
public int peek() {
if (this.isEmpty())
throw new NoSuchElementException("Stack Underflow");
return first.item;
}
}
And MyQueue file
public class Ex3_5_MyQueue {
Ex3_5_Stack StackNewest,StackOldest;
public Ex3_5_MyQueue() {
super();
StackNewest = new Ex3_5_Stack();
StackOldest = new Ex3_5_Stack();
}
public int size() {
return StackNewest.size()+StackOldest.size();
}
public void add(int value) {
StackNewest.push(value);
}
private void transferStack() {
if (StackOldest.isEmpty()) {
while (StackNewest.isEmpty()) {
StackOldest.push(StackNewest.pop());
}
}
}
public int peek() {
this.transferStack();
return StackOldest.peek();
}
public int remove() {
this.transferStack();
return StackOldest.pop();
}
public static void main(String[] args) {
Ex3_5_MyQueue myQueue = new Ex3_5_MyQueue();
myQueue.add(4);
myQueue.add(3);
myQueue.add(5);
myQueue.add(1);
System.out.println(myQueue.peek());
}
}
In transferStack(), you're missing an exclamation mark. It should be:
private void transferStack(){
if(StackOldest.isEmpty()){
while(!StackNewest.isEmpty()){ // you forgot it here
StackOldest.push(StackNewest.pop());
}
}
}

Categories