patterncsharpModerate
Stack implementation in C#
Viewed 0 times
implementationstackstackoverflow
Problem
I started to learn data structures. How can I improve my implementation? For example, I don't now how to push
0 or how to realize my own resize.public class Stack: IStack
{
private int[] s;
public Stack(int N)
{
s = new int[N];
}
public void push(int x)
{
int i = 0;
while (s[i] != 0)
{
++i;
}
if (i+1 >= s.Length)
{
Array.Resize(ref s, s.Length*2);
}
s[i] = x;
}
public int pop()
{
int i = 0;
while (i != s.Length && s[i] != 0)
{
i++;
}
s[i] = 0;
return s[i - 1];
}
}Solution
There are some problems with your code, especially
-
Naming
Names like
-
It is not possible to
-
The
-
Conventions
The default naming conventions for
Read: Naming guidelines for NET
-
You really should take care of the index of the last inserted value. This makes it easier and better to maintain if you need to pop or push.
-
Naming
Names like
s, N or x won't tell much about what they are used for. So maby slot, size and value would be a better fit. -
It is not possible to
push a 0 to the stack -
The
Stack is limited to only integers. If you want to push a decimal or a SomeClass you just can't. -
Conventions
The default naming conventions for
C# is to use PascalCase casing for naming methods, so push and pop should be Push and Pop. Read: Naming guidelines for NET
-
You really should take care of the index of the last inserted value. This makes it easier and better to maintain if you need to pop or push.
Context
StackExchange Code Review Q#106004, answer score: 16
Revisions (0)
No revisions yet.