Ognian.Kabranov
BAN USERThis is one possible solution. I am using LinkedList instead of Queue.
import java.util.LinkedList;
public class StackWithQueues<E> {
LinkedList<E> queue1=new LinkedList<E>();
LinkedList<E> queue2=new LinkedList<E>();
public void push(E e){
queue2.add(e);
while(!queue1.isEmpty()){
queue2.add(queue1.removeFirst());
}
while(!queue2.isEmpty()){
queue1.add(queue2.removeFirst());
}
}
public E pop(){
return queue1.removeFirst();
}
public static void main(String[] args){
StackWithQueues<Integer> swq=new StackWithQueues<Integer>();
swq.push(1);
swq.push(2);
swq.push(3);
swq.push(4);
System.out.println(swq.pop());
System.out.println(swq.pop());
System.out.println(swq.pop());
System.out.println(swq.pop());
}
}
Here it is:
public class MergeSortedLists {
static List<Integer> merge(List<Integer> list1, List<Integer> list2){
List<Integer> list=new LinkedList<Integer>();
int k1=0;
int k2=0;
while(k1<list1.size()&&k2<list2.size()){
if(list1.get(k1)<list2.get(k2)){
list.add(list1.get(k1++));
} else {
list.add(list2.get(k2++));
}
}
while(k1<list1.size()){
list.add(list1.get(k1++));
}
while(k2<list2.size()){
list.add(list2.get(k2++));
}
return list;
}
public static void main(String[] args){
List<Integer> list1=new LinkedList<Integer>();
List<Integer> list2=new LinkedList<Integer>();
list1.add(0);list1.add(2);list1.add(4);list1.add(6);
list2.add(1);list2.add(3);list2.add(5);
System.out.println(merge(list1,list2));
}
}
A slightly modified binary search. Here is in Java. Returns the node containing the closest data.
public Node bestLookup(Node root, int n, Node best){
if(root==null) return best;
if(root.data==n) return root;
if(Math.abs(root.data-n)<Math.abs(best.data-n)) best=root;
if(n<root.data) return bestLookup(root.left,n,best);
if(n>root.data) return bestLookup(root.right,n,best);
}
I will consider the problem as producer/consumer problem.
- producer are the cars waiting to park
- consumer are the cars parking out.
- the shared resource (buffer space) is the size of the parking.
The rest is direct implementation of the problem.
Here is my solution. The standard approach is to use stack.
- Ognian.Kabranov June 07, 2015