Can you help with this problem. Write a method destutter that accepts a Stack of
ID: 3660634 • Letter: C
Question
Can you help with this problem. Write a method destutter that accepts a Stack of integers as a parameter and removes every duplicate value in the stack with just one occurrence of that value (the stack will be entirely composed of sequentially duplicate pairs). For example, suppose a stack stores these values: bottom [3, 3, 7, 7, 1, 1, 14, 14, 9, 9] top Then the stack should store the following values after the method terminates: bottom [3, 7, 1, 14, 9] top Notice that you must preserve the original order. In the original stack the two 9s were at the top. In the new stack the one 9 would be the first value popped from the stack. If the original stack is empty, the result should be empty as well.Explanation / Answer
/*100% working code*/
import java.util.Scanner;
import java.util.Stack;
public class DeshutterTest {
static Stack<Integer> deshutter(Stack<Integer> s) {
int i;
try {
Stack<Integer> result = new Stack<Integer>();
for (i = 1; i < s.size(); i++) {
if (s.get(i) != s.get(i - 1)) {
result.add(s.get(i - 1));
}
}
result.add(s.get(i - 1));
s = result;
} catch (Exception e) {
}
return s;
}
static void print(Stack<Integer> s) {
for (int i = 0; i < s.size(); i++) {
System.out.print(s.get(i) + " ");
}
}
public static void main(String[] args) {
int numOfInt;
Stack<Integer> s = new Stack<Integer>();
Scanner input = new Scanner(System.in);
System.out
.println("Enter the no. of element want to store in stack : ");
numOfInt = input.nextInt();
for (int i = 1; i <= numOfInt; i++) {
System.out.println("Enter the element :" + i + " :");
s.push(input.nextInt());
}
System.out.print("bottom[");
print(s);
System.out.println("]top");
s = deshutter(s);
System.out.print("bottom[");
print(s);
System.out.print("]top");
}
}
Output:-
Enter the no. of element want to store in stack : 10
Enter the element :1 :3
Enter the element :2 :3
Enter the element :3 :7
Enter the element :4 :7
Enter the element :5 :1
Enter the element :6 :1
Enter the element :7 :14
Enter the element :8 :14
Enter the element :9 :9
Enter the element :10 :9
bottom[3 3 7 7 1 1 14 14 9 9 ]top
bottom[3 7 1 14 9 ]top