driveway is a \"last-in, first-out\" stack. Of course, when a car owner retrieve
ID: 3553707 • Letter: D
Question
driveway is a "last-in, first-out" stack. Of course, when a car owner retrieves a vehicle that wasn't the last one in, the cars blocking it must temporarily move to the street so that the requested vehicle can leave. Write a program in Java that models this behavior, using one stack for the driveway and one stack for the street. Use integers as license plate numbers. Positive numbers add a car, negative numbers remove a car, zero stops the simulation. Print out the stack after each operation is complete.
Explanation / Answer
package com.sampath.algorithms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Stack;
public class Driveway {
private static Stack driveway = new Stack();
private static Stack street = new Stack();
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n=0;
System.out.println("Enter the value:");
while((n=(Integer.parseInt(reader.readLine())))!=0){
if(n>0)
push(n);
else
pop(n);
show(driveway);
System.out.print("Enter the value:");
}
}
// To print the stack results for each operation
private static void show(Stack driveway) {
Iterator itr = driveway.iterator();
System.out.print("Here is cars: ");
while(itr.hasNext()){
System.out.print(itr.next());
System.out.print(" ");}
System.out.println();
}
//To push the car into driveway stack
public static void push(int n){
if(!driveway.contains(n))
driveway.push(n);
}
//To pop from driveway stack
public static void pop(int n){
int k=0;
while((k=(Integer) driveway.pop())!=n*-1)
street.push(k);
System.out.println("Require Car is:"+k);
while(!street.empty())
driveway.push(street.pop());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.