Quantcast
Channel: User user2023861 - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 35

Answer by user2023861 for Stack implementation in C#

$
0
0

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 the lastIndex 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;    }}

Viewing all articles
Browse latest Browse all 35

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>