I have implemented in C# a stack data structure, without using any existing C#/.NET containers (data structures). I have used TDD technique to implement this requirements, so you can find tests, too. All my tests are passing, so I guess stack is behaving correctly.
I would be very pleased to have a code review for this implementation.
Please do not recommend a generic implementation :-)
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StackDataStructure;
namespace StackTesting
{
[TestClass]
public class Tests
{
[TestMethod]
public void TestEmptyStackSize()
{
var stack = new Stack();
Assert.IsTrue(stack.IsEmpty());
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void EmptyStackPopException()
{
var stack = new Stack();
stack.Pop();
}
[TestMethod]
public void PushingAndPoppintItemsToStack()
{
var stack = new Stack();
stack.Push(1);
Assert.AreEqual(1, stack.Size);
stack.Push(2);
Assert.AreEqual(2, stack.Size);
Assert.AreEqual(2, stack.Pop());
Assert.AreEqual(1, stack.Size);
Assert.AreEqual(1, stack.Pop());
Assert.IsTrue(stack.IsEmpty());
Assert.IsTrue(stack.Size == 0);
stack.Push(10);
Assert.IsTrue(stack.Size == 1);
Assert.IsTrue(10 == stack.Pop());
Assert.IsTrue(stack.IsEmpty());
}
}
}
using System;
namespace StackDataStructure
{
internal class Node
{
internal int value;
internal Node underTop;
}
public class Stack
{
private int size;
private Node top;
public int Size { get { return size; } }
public bool IsEmpty()
{
return top == null;
}
public int Pop()
{
if (IsEmpty())
throw new InvalidOperationException("Stack is empty");
int value = top.value;
top = top.underTop;
size--;
return value;
}
public void Push(int v)
{
top = new Node{
value = v,
underTop = top
};
size++;
}
}
}