Check whether each pair of adjacent numbers in the stack is continuous (JAVA)

problem

Given a stack, how to check whether each pair of adjacent numbers in the stack is continuous, the value of each pair of numbers can be incremented or decremented, if
the number of elements in the stack is odd, then the top element of the stack is ignored when teaming, for example, suppose The elements in the stack are [4,5,-2,-3,11,10,5,6,20], then the output of the algorithm is true, because for the two-tuple (4,5), (-2,-3) , (11,10) and (5,6) are consecutive numbers

  /**
     * 检查整数栈没对相邻数字连续
     *
     * @param s
     * @return
     */
    public static boolean checkStackPairwiseOrder(Stack<Integer> s) {
    
    
        Queue<Integer> q = new LinkedList<>();
        boolean pairwiseOrdered = true;
        while (!s.isEmpty()) {
    
    
            q.add(s.pop());
        }
        while (!q.isEmpty()) {
    
    
            s.push(q.remove());
        }
        while (!s.isEmpty()) {
    
    
            int n = s.pop();
            q.add(n);
            if (!s.isEmpty()) {
    
    
                int m = s.pop();
                q.add(m);
                if (Math.abs(n - m) != 1) {
    
    
                    pairwiseOrdered = false;
                }
            }
        }
        while (!q.isEmpty()) {
    
    
            s.push(q.remove());
        }
        return pairwiseOrdered;
    }

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/108817709