In: Computer Science
please in java !
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.
A)Solution:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Stack<Integer> ourStack = new Stack<Integer>();
Stack<Integer> pos = new Stack<Integer>();
Stack<Integer> res = new Stack<Integer>();
ourStack.push(1);
ourStack.push(3);
ourStack.push(-2);
ourStack.push(-8);
ourStack.push(5);
ourStack.push(6);
ourStack.push(-4);
ourStack.push(-5);
for(int i=0;i<ourStack.size();i++){
if(ourStack.get(i)>0){
pos.push(ourStack.get(i));
}
}
int i=0,j=0;
while(i<pos.size()&&j<ourStack.size()){
if(ourStack.get(j)<0){
res.push(pos.get(i));
res.push(ourStack.get(j));
i++;
}
j++;
}
System.out.println(res);
}
}
B)SOLUTION:
import java.util.*;
class test{
public LinkedList<Integer> ourList=new LinkedList<Integer>();
public test( LinkedList<Integer> ourList){
this.ourList=ourList;
}
public void insertFront(int i){
ourList.addFirst(i);
}
public void insertBack(int i){
ourList.add(i);
}
public void removeFront(){
ourList.remove(0);
}
public void remmoveLast(){
ourList.remove(ourList.size()-1);
}
public boolean isEmpty(){
return ourList.isEmpty();
}
}
public class MyClass {
public static void main(String args[]) {
List<Integer> ourList = new ArrayList<Integer>();
List<Integer> pos = new ArrayList<Integer>();
List<Integer> res = new ArrayList<Integer>();
ourList.add(1);
ourList.add(3);
ourList.add(-2);
ourList.add(-8);
ourList.add(5);
ourList.add(6);
ourList.add(-4);
ourList.add(-5);
for(int i=0;i<ourList.size();i++){
if(ourList.get(i)>0){
pos.add(ourList.get(i));
}
}
int i=0,j=0;
while(i<pos.size()&&j<ourList.size()){
if(ourList.get(j)<0){
res.add(pos.get(i));
res.add(ourList.get(j));
i++;
}
j++;
}
System.out.println(res);
}
}
Thank you! if you have any queries post it below in the comment
section I will try my best to resolve your queries and I will add
it to my answer if required. Please give upvote if you like
it.