In: Computer Science
Assume you have a stack of integers. The stack contains same number of positive and negative integers. You want to organize it such that negative and positive integers alternate (+-+-.., or -+-+,..).
A. Write a Java code that uses no more than two additional Stacks to solve the problem.
Note: You do not need to write the code for Stacks, you are using a Stack from the library with a name ourStack and has the following interface: ourStack() constructor, pop, push, isEmpty, size(), peek()).
B- Solve the same problem using one temporary list with interface: ourList() constructor, insertFront, insertBack, removeFront, removeBack, isEmpty, size().
Bonus Can you solve the problem using one queue (ourQueue with interface (add, remove, isEmpty, size() and peek() that returns the front without removing it).
Big Bonus: Solve the problem using only one temporary stack.
This question is for my midterm. please I need comments on the code.
the code below is a code that pro covered in class for the stacks and he expect something like that.
public class ourStack<T> { private T[] S; private int size = 0; public ourStack() { S = (T[]) new Object[100]; size = 0; } public int size() { return size; } public boolean isEmpty() { return (size == 0? true:false); } //index size is the empty spot. public void push(T e) { if(size == S.length) this.resize(); this.S[size] = e; size++; } public T pop() { if(this.isEmpty()) return null; size--; return this.S[size]; } public T peek() { if(this.isEmpty()) return null; return this.S[size - 1]; } private void resize() { //create an array temp of length Ar.length + 100 T[] temp = (T[]) new Object[this.S.length+100]; //copy array Ar into array temp for(int i = 0; i<S.length; i++) temp[i] = this.S[i]; //assign temp to Ar. this.S = temp; } //write a toString to return the content of the array in the form [-3, -2, -5] public String toString() { String st = "["; if(this.isEmpty()) return "[]"; for (int i = 0; i<size -1; i++) { st += this.S[i] + ", "; } st += this.S[size - 1] + "]"; return st; } }
Of all the ways to solve this problem, I went for the most optimized one so that you can get that BIG BONUS. I used the stack class provided in the question for stack functions.
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args){
ourStack<Integer> s1 = new ourStack<Integer>();
s1.push(5);
s1.push(3);
s1.push(2);
s1.push(-1);
s1.push(-6);
s1.push(8);
s1.push(-9);
s1.push(-4);
ourStack<Integer> s2 = new ourStack<Integer>();
int a=s1.peek();
while(s1.isEmpty()==true || s2.isEmpty()==true){
while(s1.size()>0){
if(s1.peek()>0 && a>0){
a=s1.pop();
s2.push(a);
}else if(s1.peek()<0 && a<0){
a=s1.pop();
s2.push(a);
}else{
a=s1.pop();
System.out.print(a+" ");
}
}
while(s2.size()>0){
if(s2.peek()>0 && a>0){
a=s2.pop();
s1.push(a);
}else if(s2.peek()<0 && a<0){
a=s2.pop();
s1.push(a);
}else{
a=s2.pop();
System.out.print(a+" ");
}
}
}
}
}
(Throw an upvote or comment if you have any doubts.)