【发布时间】:2021-06-19 14:07:44
【问题描述】:
我正在使用堆栈对另一个堆栈进行排序,只要 stack1.peek > stack2.peek 将所有节点从堆栈 1 转移到堆栈 2。如果 stack1.peek 小于 stack 2.peek,我将所有大于 stack1.peek 的节点移动到 stack 1。
在 else if 块中,当堆栈 2 暂时为空时会出现问题。如何编写代码以忽略此异常?即使堆栈 2 暂时为空,我也需要循环继续运行。
这是代码:
import java.util.*;
public class SortedStack {
/*
* Method
*
* Stack 1 is the original stack
* Stack 2 is the helper stack
*/
public static void sortStack(Stack<Integer> stack1) {
// second, helper stack:
Stack<Integer> stack2 = new Stack<Integer>();
int count = 0;
// loop through each node in stack 2, compare to current node at top of stack 1
while (!stack1.isEmpty()) { // loop until entire stack 1 is sorted
int temp1 = stack1.pop();
// 1. STACK 2 IS EMPTY
if (stack2.isEmpty()) { // if stack 2 is empty and we're at the beginning of the problem
stack2.push(temp1);
}
// IF STACK 1 NODE < STACK 2 NODE
else if (temp1 < stack2.peek()) {
// If the S1 node is smaller than the top S2 node, we need to rearrange things.
// All nodes in S2 that are bigger than S1 temp are transferred to S1, and then added back once S1 temp is pushed into S2
while (temp1 < stack2.peek()) {
int temp2 = stack2.pop();
stack1.push(temp2);
count++;
}
// add top node of S1 to stack 2
stack2.push(temp1);
// add these nodes back to stack 2
while (count >0) {
int temp3 = stack1.pop();
stack2.push(temp3);
count--;
}
}
// IF STACK 1 NODE > STACK 2 NODE
else { // (temp1 > stack2.peek())
stack2.push(temp1); // if the S1 node is bigger than the S2 top node, we just add the S1 node over to S2
}
}
System.out.println(stack2.toString());
}
// Run the method
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.add(34);
stack.add(3);
stack.add(31);
stack.add(98);
stack.add(92);
stack.add(23);
sortStack(stack);
}
}
谢谢!
【问题讨论】:
标签: java sorting exception stack