繁体   English   中英

堆栈模拟不存储元素

[英]Stack simulation not storing elements

public class Stack {
    Student Sarray[] = new Student[1000];
    int nrElem=0;

    public Student[] getAll(){
        return this.Sarray;
    }

    public void push(Student x){

        this.nrElem++;  
        this.Sarray[this.nrElem]=x;
    }
}

我尝试手动实现堆栈,我有一点问题。我插入的第一个元素存储并替换当我插入另一个。我做错了什么?

public class Ctrl {
    Stack x = new Stack();
public void addC(Student s){
    if(findById(s.getId()) != null) {
        System.out.println("Err!Duplicate id!/n");  
    } else {
        if(s.getGrade()>10)
            System.out.println("Err!Grade bigger than 10!/n");  
        else{ 
        x.push(s);
        }
    }
}



public Student findById(int id){
    Stack y=new Stack();
    y=x;
    Student z= new Student() ;

    for(int i=1;i<=y.getNrElem();i++){
        z=y.pop();
        if (z.getId()==id) 
            return z;
    }
    return null;    
}

Stack和Ctrl的2个不同模块。

public Student findById(int id)你这样做:

Stack y=new Stack(); // creates new reference to new Stack ...
y=x;                 // reference is redirected to point to the class's Stack instance

y现在指向类成员x,在后续循环中将其弹出为空。 这意味着如果使用ref y对数据结构进行更改,则可以使用ref x查看这些更改,因为您正在对同一实例进行更改。

您可以在Stack-Class中实现不会更改Stack内容的搜索,也可以在Stack的副本上实现此搜索。 大多数情况下,这是通过在DataStructure的类中提供“复制”-Constructor或“clone()”方法来实现的。

例如,将上面的行更改为

Stack y = new Stack(x);
// y=x We do not need this any more.

在Stack类中添加:

public Stack( Stack aStack ) {
    System.arraycopy(aStack.Sarray,0,this.Sarray,0,aStack.Sarray.length);
    // By the way: please start members with a small letter!

    this.nrElem = aStack.nrElem;
}

PS:并注意到RamonBoza的评论,为他+1。

您正在使用addC方法插入学生。 它又调用findById ,其中包含以下行:

z=y.pop()

对于简单的情况,在弹出它的堆栈中有一个元素,但永远不会将其推回。 因此,要修复它,您需要在弹出它们之后将元素返回到堆栈,或者在Stack类中找到一个方法来查找元素而不将它们弹出。

顺便说一句,你还没有提供getNrElem()方法的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM