Skip to content

Instantly share code, notes, and snippets.

@zihotki
Created May 31, 2016 21:03
Show Gist options
  • Save zihotki/acdca63181656cae932724d104c4d25c to your computer and use it in GitHub Desktop.
Save zihotki/acdca63181656cae932724d104c4d25c to your computer and use it in GitHub Desktop.
Stack implementation using recursive links
using System;
public class Program
{
public static void Main()
{
var stack = new Stack();
stack.Push(5);
stack.Push(4);
stack.Push(3);
Console.WriteLine("Hello World");
Console.WriteLine("count " + stack.Count);
Console.WriteLine("popped value " + stack.Pop());
Console.WriteLine("count " + stack.Count);
Console.WriteLine("peeked value " + stack.Peek());
Console.ReadLine();
}
}
public class Stack
{
private Stack _current;
private Stack _previous;
private int? _value;
private int _count = 0;
public int Count { get { return _current._count; } }
public Stack()
{
_current = this;
}
protected Stack(int value, Stack previous)
{
_current = this;
_value = value;
_count = previous._count + 1;
_previous = previous;
}
public void Push(int value)
{
_previous = _current;
_current = new Stack(value, _current);
}
public int? Peek()
{
return _current._value;
}
public int? Pop()
{
if (this == _current)
{
return _current._value;
}
// swap
var current = _current;
_current = _previous;
// clean
current._previous = null;
current._current = null;
return current._value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment