Challenge:
Implement a stack interface.
Specifications:
The interface should have ‘push’ and ‘pop’ functions.
Your task is to ‘push’ a series of integers and then ‘pop’ and print every alternate integer.
Your program should accept a file as its first argument.
The file contains a series of space delimited integers, one per line.
Print out every alternate space delimited integer, one per line.
Solution:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;
public class Stack<T> {
LinkedList<T> list = new LinkedList<>();
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File(args[0]));
while (input.hasNextLine()) {
System.out.println(
retrieveAlternates(input.nextLine().split("\\s+"))
);
}
}
private static String retrieveAlternates(String[] input) {
Stack<Integer> stack = new Stack<>();
StringBuilder result = new StringBuilder();
for (String s : input) {
stack.push(Integer.parseInt(s));
}
for (int i = 0; i < input.length; i++) {
if ((i & 1) == 0) {
result.append(' ').append(stack.pop());
} else {
stack.pop();
}
}
return result.substring(1);
}
public void push(T t) {
list.add(t);
}
public T pop() {
return list.removeLast();
}
}
Tests:
@Test
public void test1 {
assertEquals("4 2", Stack.retrieveAlternates("1 2 3 4"));
}
@Test
public void test2 {
assertEquals("4 -2", Stack.retrieveAlternates("10 -2 3 4"));
}
I've never really had an "Implement X" challenge, before. This passed, but did I effectively do what was expected? Could it be better?