Going off your question about pushing zeroes onto the stack, another user mentioned that you should keep an index into the stack to remember where to push and pop. I've updated your code only addressing that point:
Notice a couple of points:
- You can insert zeroes. Notice in the code that I don't compare the values in the array to
0
anywhere. I instead use thelastIndex
integer as a pointer into the stack. - In both the push() and pop() methods, I removed your while loops while keeping the functionality. Your methods ran in linear time because of these loops. My versions run in constant time (except for the array resize).
Code:
public class MyStack{ private int[] s; private int lastIndex = 0; public MyStack(int N) { s = new int[N]; } public void push(int x) { //no need for your while loop //this condition replaces your "i + 1 >= s.Length" condition if (lastIndex == s.Length) { Array.Resize(ref s, s.Length * 2); } //replaces your "s[i] = x" s[lastIndex] = x; //this updates the pointer to where the next push will be lastIndex++; } public int pop() { //This moves the pointer to the newest item lastIndex--; //This replaces your while loop int result = s[lastIndex]; return result; }}