Sorting a stack (the stack through an auxiliary)

 

Problem Description:

A conventional stack, comprising a number of integer elements, is required in the end of this stack in descending order from the top (only allowed to apply a new stack).

 

Algorithm:

public void sortStackByStack(Stack<Integer> stack) {

Stack<Integer> help = new Stack<>();

while (!stack.isEmpty()) {

int cur = stack.pop();
while (!help.isEmpty() && help.peek() < cur) {
stack.push(help.pop());
}
help.push(cur);
}

while (!help.isEmpty()) {

stack.push(help.pop());
}

}

 

Algorithm Analysis:

1. Application of a new stack, the stack space by the characteristics of both the stack and the element and through comparison rule out certain operations in the two stacks in the stack, to achieve an ordered stack;

2. during operation, mainly related to the stack if the stack to the stack of each comparison element is empty judgment and the auxiliary stack and the elements to be sorted;

3. Draw the two sheet stack, or two stacks contemplated in the brain, in conjunction with the code and constant out analog comparator stack operations.

 

Guess you like

Origin www.cnblogs.com/heibingtai/p/12637836.html