11package com .thealgorithms .stacks ;
22
3+ import java .util .ArrayDeque ;
4+ import java .util .Deque ;
35import java .util .Scanner ;
4- import java .util .Stack ;
56import java .util .function .BiFunction ;
67
78/**
@@ -35,24 +36,23 @@ private static BiFunction<Integer, Integer, Integer> getOperator(final String op
3536 }
3637 }
3738
38- private static void performOperation (Stack <Integer > s , final String operationSymbol ) {
39+ private static void performOperation (Deque <Integer > s , final String operationSymbol ) {
3940 if (s .size () < 2 ) {
4041 throw new IllegalArgumentException ("exp is not a proper postfix expression (too few arguments)." );
4142 }
4243 s .push (getOperator (operationSymbol ).apply (s .pop (), s .pop ()));
4344 }
4445
45- private static void consumeExpression (Stack <Integer > s , final String exp ) {
46- Scanner tokens = new Scanner (exp );
47-
48- while (tokens .hasNext ()) {
49- if (tokens .hasNextInt ()) {
50- s . push ( tokens . nextInt ());
51- } else {
52- performOperation ( s , tokens . next ());
46+ private static void consumeExpression (Deque <Integer > s , final String exp ) {
47+ try ( Scanner tokens = new Scanner (exp )) {
48+ while ( tokens . hasNext ()) {
49+ if (tokens .hasNextInt ()) {
50+ s . push (tokens .nextInt ());
51+ } else {
52+ performOperation ( s , tokens . next ());
53+ }
5354 }
5455 }
55- tokens .close ();
5656 }
5757
5858 /**
@@ -62,7 +62,7 @@ private static void consumeExpression(Stack<Integer> s, final String exp) {
6262 * @exception IllegalArgumentException exp is not a valid postix expression.
6363 */
6464 public static int postfixEvaluate (final String exp ) {
65- Stack <Integer > s = new Stack <>();
65+ Deque <Integer > s = new ArrayDeque <>();
6666 consumeExpression (s , exp );
6767 if (s .size () != 1 ) {
6868 throw new IllegalArgumentException ("exp is not a proper postfix expression." );
0 commit comments