import java.util.Stack;
public class PairwiseConsecutiveChecker {
public static boolean arePairwiseConsecutive(Stack<Integer> stack) {
Stack<Integer> temp = new Stack<>();
// Reverse stack into temp to preserve original order
while (!stack.isEmpty()) {
temp.push(stack.pop());
}
boolean result = true;
// Check pairs while restoring original stack
while (!temp.isEmpty()) {
int first = temp.pop();
stack.push(first); // restore
if (!temp.isEmpty()) {
int second = temp.pop();
stack.push(second); // restore
if (Math.abs(first - second) != 1) {
result = false;
}
}
}
return result;
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
s.push(4);
s.push(5);
s.push(9);
s.push(10);
s.push(18);
s.push(19);
System.out.println(arePairwiseConsecutive(s));
System.out.println(s);
}
}
/*
run:
true
[4, 5, 9, 10, 18, 19]
*/