Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

arrays - How does one replace last element of full stack with new element? (java)

public class ourStack1 {
    private int elements[];
    private int index;      // indicate the next position to put a new data
    private int size;
    
    public ourStack1() {
        elements = new int[10];
        index = 0;
        size = 0;
    }
    
    public void push(int value) {
        if(size == 10) {
            System.out.println("Stack is full, no push");
            return;
        }
        elements[index] = value;
        ++index;
        ++size;
    }
    
    public int pop() {
        if(size == 0) {
            System.out.println("Stack is empty, no pop");
            return -1;
        }
        int temp = elements[index - 1];
        --index;
        --size;
        return temp;
    }
    
    public int peek() {
        if(size == 0) {
            System.out.println("Stack is empty, no peek");
            return -1;
        }
        return elements[index - 1];
    }
    
    /*
    public int mySize() {
        // you know how to do this
    }
    */
    
    public static void main(String[] args) {
        ourStack1 x = new ourStack1();
        for(int i = 0; i < 10; ++i)
            x.push(i);
        for(int i = 0; i < 10; ++i)
            System.out.println(x.pop());
    }
}

I'm confused on how to overwrite the last element added to the full stack. I want to add element to replace the last element while not exceeding the array size[10]

question from:https://stackoverflow.com/questions/65939665/how-does-one-replace-last-element-of-full-stack-with-new-element-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public void replaceLast(int value) {
  if (this.size > 0) {
    this.pop();
  }
  this.push(value);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...