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
Related
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());
}
}
public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}
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
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() {
...
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());
}
}
}