如何借助辅助栈,仅用peek、push、pop向Java栈底添加元素
Alright, let's tackle this problem head-on. You've got a stack stackA loaded with 10 integers, and you need to tuck a specified element right at its bottom—with only peek(), push(), and pop() allowed. No sneaky workarounds like accessing the stack's underlying structure. Here's a straightforward, efficient way to do it:
The Core Logic
Stacks follow LIFO (Last-In-First-Out) rules, so we can't reach the bottom directly. Instead, we'll use the auxiliary stack stackB as a temporary storage bin: we'll empty stackA into stackB, drop our target element into the now-empty stackA, then move everything back from stackB to stackA. That way, the new element stays locked at the bottom.
Full Implementation Code
Here's the complete addOnBeginning method (I adjusted the spelling for clarity) plus a test setup to verify the result:
import java.util.Stack; public class StackBottomAdder { public static void main(String[] args) { // Initialize stackA with 1-10 as specified Stack<Integer> stackA = new Stack<>(); stackA.push(1); stackA.push(2); stackA.push(3); stackA.push(4); stackA.push(5); stackA.push(6); stackA.push(7); stackA.push(8); stackA.push(9); stackA.push(10); // Add element 0 to the bottom of stackA addOnBeginning(stackA, 0); // Print elements to confirm the order (stack pops from top, so output will be 10 9 ... 1 0) while (!stackA.isEmpty()) { System.out.print(stackA.pop() + " "); } } public static void addOnBeginning(Stack<Integer> stackA, int element) { Stack<Integer> stackB = new Stack<>(); // Step 1: Move every element from stackA to stackB while (!stackA.isEmpty()) { stackB.push(stackA.pop()); } // Step 2: Push our target element to the empty stackA (this becomes the new bottom) stackA.push(element); // Step 3: Move all elements back from stackB to stackA, restoring original order above the new element while (!stackB.isEmpty()) { stackA.push(stackB.pop()); } } }
Let's Walk Through It
- Step 1: We drain
stackAby popping each element and pushing it tostackB. After this,stackBholds elements in reverse order (10 at the top, 1 at the bottom) andstackAis empty. - Step 2: Pushing our target element to the empty
stackAensures it's the first (and only) element—so it's firmly at the bottom. - Step 3: We pop elements from
stackBand push them back tostackA, which rebuilds the original stack order but now with our new element sitting at the very base.
Verify the Result
When you run the code, the output will be 10 9 8 ... 1 0. Don't worry about the reverse order in the printout—that's just because we're popping elements from the top to display them. Under the hood, the stack's structure is exactly what you want: [0,1,2,...,10] from bottom to top.
内容的提问来源于stack exchange,提问作者John Williams

