数据结构Stack实践问题:pop()输出末尾值为null的原因排查
自定义栈输出null的原因分析
错误根因
- push()溢出判断逻辑错误:你的栈数组
String stack[] = new String[5]有效索引范围为0~4,且你定义top为「下一个可插入元素的位置」(每次存入stack[top]后执行top++)。栈满的判断条件应当是top >= 数组长度(即5),但你写的判断条件是top >=4,导致第5个待入栈的字符e直接触发溢出判断,根本没有被存入stack[4]。Java中字符串数组的元素默认值为null,这就是输出中出现null的直接来源。 - pop()循环逻辑错误:执行完4次有效入栈操作后,
top值停留在4(第5次入栈触发溢出未修改top)。你的pop循环从i=top=4开始,直接读取stack[4]的null值,随后才依次读取到stack[3]~stack[0]的d/c/b/a,最终共输出5行结果,第一行就是无效的null。 - 附加逻辑错误:栈的下溢判断条件错误,按你的top定义,栈空时
top=0,但你判断下溢的条件是top == -1,永远无法触发下溢提示;peek()方法没有做越界判断,也缺失输出逻辑。
修正后代码实现
Stack类
package stack; public class Stack { int top = 0; // 表示下一个可插入元素的位置,栈空时top=0 String stack[] = new String[5]; int capacity = stack.length; public void push(String val) { if(top >= capacity) { System.out.println("Overflow Condition"); return; } stack[top] = val; System.out.println("new value for index " + top + " is " + stack[top]); top++; } public String pop() { if(top == 0) { System.out.println("Underflow Condition"); return null; } top--; String removedVal = stack[top]; System.out.println("Removed Index: " + top + " is " + removedVal); return removedVal; } public String peek() { if(top == 0) { System.out.println("Stack is Empty"); return null; } return stack[top - 1]; } }
Main类(实现5个字符入栈后反转输出)
package stack; import java.util.Scanner; public class StackHome { public static void main(String[] args) { Scanner inp = new Scanner(System.in); Stack obj = new Stack(); String arr[] = new String[5]; for(int i = 0; i < 5; i++) { System.out.println("Value to add for stack"); String value = inp.next(); arr[i] = value; obj.push(arr[i]); } System.out.println("--- Reversed Output ---"); while(obj.top > 0) { obj.pop(); } inp.close(); } }
修正后运行效果(输入a/b/c/d/e)
Value to add for stack a new value for index 0 is a Value to add for stack b new value for index 1 is b Value to add for stack c new value for index 2 is c Value to add for stack d new value for index 3 is d Value to add for stack e new value for index 4 is e --- Reversed Output --- Removed Index: 4 is e Removed Index: 3 is d Removed Index: 2 is c Removed Index: 1 is b Removed Index: 0 is a
内容的提问来源于stack exchange,提问作者Jehan Fernando
相关产品推荐
相关产品推荐

