Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...