编写代码,将10个字符串推入堆栈(版本2),打印时打印,然后将其弹出,打印时删除。
import java.math.*;
public class StackTest {
public static void main (String[] args){
Stack2 stk = new Stack2("Stack");
for(int i = 0; i < 10; i++){
stk.push("Item: " + (i + 1));
System.out.println("Pushing: Item: " + (i + 1));
}
System.out.println("\n" + stk.print());
for(int i = 0; i < 10; i++){
System.out.println("Popping: " + stk.pop());
}
System.out.println("\n" + stk.print());
}
}
答案 0 :(得分:2)
你有一个测试你的自定义Stack实现的TestClass。
你需要知道关于堆栈的一些关键事项是:
LIFO(后进先出)数据结构
这在您的浏览器中使用。单击后退按钮时。
带您到访问过的最后一页。
// A class in the default package
// Import java.math
import java.math.*;
// Class Name: StackTest
public class StackTest {
// Your main method: The entry point of your program
public static void main (String[] args){
// Creates an object Stack2 and references it to stk
Stack2 stk = new Stack2("Stack");
// Runs a for loop 10 times and pushes an element into the stack and prints the result into the console
for(int i = 0; i < 10; i++){
stk.push("Item: " + (i + 1));
System.out.println("Pushing: Item: " + (i + 1));
}
// Prints your stack
System.out.println("\n" + stk.print());
// Runs a loop 10 times and pops each item of the stack out
for(int i = 0; i < 10; i++){
System.out.println("Popping: " + stk.pop());
}
// Prints your stack
System.out.println("\n" + stk.print());
}
}
你的控制台会读到这样的内容:
Pushing Item: Item 1
Pushing Item: Item 2
Pushing Item: Item 3
Pushing Item: Item 4
Pushing Item: Item 5
Pushing Item: Item 6
Pushing Item: Item 7
Pushing Item: Item 8
Pushing Item: Item 9
Pushing Item: Item 10
Stack [Item 10, Item 9, Item 8, Item 7, Item 6, Item 5, Item 4, Item 3, Item 2, Item 1] < depending on what your Stack2 print() method does.
Popping: Item 10
Popping: Item 9
Popping: Item 8
Popping: Item 7
Popping: Item 6
Popping: Item 5
Popping: Item 4
Popping: Item 3
Popping: Item 2
Popping: Item 1
Stack []