Coding exercise: code must be written ready for execution and can be implemented
ID: 3812475 • Letter: C
Question
Coding exercise: code must be written ready for execution and can be implemented in either C or Java.
Implement insertion (or push) and deletion (or pop) for a stack and a circular queue with length of n keys as defined in class.
Input: list of pairs of an integer and an operation, e.g. 1.in 3.in 5.in 3.del 2.in .. or 10 1.push 2.push 5.push 3.pop 2.push *note that the 10 before 1.push is the length of the queue *Note that input is to be read from a file in a batch. In queue*
Output: the list before operation and the list after operation displayed on the screen standard outout (not into a file) Notice that for stack, 3.del is invalid so just ignore 3 or just perfom "del".
A command line user interface has to be provided as follow: "enter your input file name"
***First question I asked was done perfectly: http://www.chegg.com/homework-help/questions-and-answers/coding-excercise-create-executable-program-implemented-using-c-java-implement-insertion-de-q19162010***
Thanks
Explanation / Answer
CodingExercise.java :
__________________
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class CodingExercise {
public static void main(String args[]) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("enter your input file name");
String fname = sc.next();
ArrayList<Integer> al = new ArrayList<Integer>();
FileReader fr = new FileReader(fname);
BufferedReader br = new BufferedReader(fr);
String line = null;
while((line = br.readLine())!= null){
String a[] = line.split(" ");
System.out.println(" ");
for(int i=0;i<a.length;i++){
String op[] = a[i].split(",");
if(op[1].equals("in")){
al.add(new Integer(op[0]));
System.out.println(op[0]+" is pushed into stack");
}
else if(op[1].equals("del")){
al.remove(new Integer(op[0]));
System.out.println(op[0]+" is poped from stack");
}
}
System.out.println(" Stack is:");
for(int j = al.size()-1;j>=0;j--)
System.out.print(al.get(j)+" ");
}
}
}
input.txt :
________
1,in 3,in 5,in 3,del
2,in 6,in 5,del 4,in
9,in 7,in 23,in 30,in 1,del
Sample Input and Output:
______________________
enter your input file name
F:\input.txt
1 is pushed into stack
3 is pushed into stack
5 is pushed into stack
3 is poped from stack
Stack is:
5 1
2 is pushed into stack
6 is pushed into stack
5 is poped from stack
4 is pushed into stack
Stack is:
4 6 2 1
9 is pushed into stack
7 is pushed into stack
23 is pushed into stack
30 is pushed into stack
1 is poped from stack
Stack is:
30 23 7 9 4 6 2