【发布时间】:2020-10-24 23:11:24
【问题描述】:
无法通过此代码实现堆栈...
UseStack.java
class UseStack{
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the size of Stack....");
int n = obj.nextInt();
Push push = new Push(n);
Pop pop = new Pop(n);
while(true){
System.out.println("1: Push");
System.out.println("2: pop");
System.out.println("3: Show");
int choice = obj.nextInt();;
switch(choice){
case 1:
push.push();
break;
case 2:
pop.pop();
break;
case 3:
push.show();
break;
default:
System.out.println("Invalid Option");
break;
}
}
}
}
Stack.java
class Stack {
public int arr[];
public int top;
public int capacity;
Stack(int size){
this.arr = new int[size];
this.capacity = size;
this.top = -1;
}
}
Push.java
class Push extends Stack {
Push(int size) {
super(size);
}
private static Scanner obj;
public void push(){
obj = new Scanner(System.in);
System.out.println("Enter Value to push...");
int value = obj.nextInt();
System.out.println("Value : "+value);
if(top==capacity-1){
System.out.println("StackOverflow");
return;
}
else{
top++;
System.out.println("Top : "+top);
arr[top]=value;
System.out.println("Pushed... "+arr[top]);
}
}
public void show(){
if(top==-1){
System.out.println("StackUnderFlow");
return;
}
else{
System.out.println("Stack Elements : ");
for(int i=top;i>=0;i--){
System.out.println(arr[i]+" ");
}
}
}
}
Pop.java
public class Pop extends Stack {
Pop(int size) {
super(size);
}
public void pop(){
if(top==-1){
System.out.println("StackUnderflow-pop");
return;
}
else{
System.out.println("Top : "+top);
System.out.println("Poped.. "+arr[top]);
top--;
}
}
}
问题
在这个实现中 pop() 不起作用.....
我认为这个 Pop 类需要同时扩展 Stack 和 Push 类,因此这在 java 中是不可能的,如果我错了,谁能帮我解决这个问题...
【问题讨论】:
-
为什么 push 和 pop(它们是 操作)会扩展
Stack类?你不会写Dog extends Animal和Bark extends Dog吧? -
@Kayaman 先生,您能否更正我一下
-
你不用叫我先生。我只是问你为什么有
Push和Pop课程?为什么push()和pop()方法不存在于Stack类中? -
您需要在问题中包含任何错误。但是代码是设计错误的,所以你应该先修复你的设计(删除
Push和Pop类),然后尝试让你的代码工作。 -
问题是 push 和 pop 不能在同一个数据结构上工作。当用户发出“推送”命令时,您在
push堆栈上调用push(),数据因此被添加到push堆栈中;同时“pop”堆栈仍然是空的。现在,当用户发出“弹出”命令时,您调用了pop堆栈的pop()方法,并且没有任何内容可以从空的pop堆栈中弹出。