????????宀�??浼�??
?????????????浼�?????????????????????????????????屑????????????眉?????????????????????貌???浼�??????????????????????????????????????????????????????????????????????????????????????????????锟�?
public interface IStack<T> : IEnumerable<T>
{
IStack<T> Push(T value);
IStack<T> Pop();
T Peek();
bool IsEmpty { get; }
}
public sealed class Stack<T> : IStack<T>
{
private sealed class EmptyStack : IStack<T>
{
public bool IsEmpty { get { return true; } }
public T Peek() { throw new Exception("Empty stack"); }
public IStack<T> Push(T value) { return new Stack<T>(value?? this); }
public IStack<T> Pop() { throw new Exception("Empty stack"); }
public IEnumerator<T> GetEnumerator() { yield break; }
IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }
}
private static readonly EmptyStack empty = new EmptyStack();
public static IStack<T> Empty { get { return empty; } }
private readonly T head;
private readonly IStack<T> tail;
private Stack(T head?? IStack<T> tail)
{
this.head = head;
this.tail = tail;
}
public bool IsEmpty { get { return false; } }
public T Peek() { return head; }
public IStack<T> Pop() { return tail; }
public IStack<T> Push(T value) { return new Stack<T>(value?? this); }
public IEnumerator<T> GetEnumerator()
{
for (IStack<T> stack = this; !stack.IsEmpty; stack = stack.Pop())
yield return stack.Peek();
}
IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }
}
?????????????????????????
??????????????????????????????????Head位???????????????Tail位??????
????????????????????Tail??????????
??????梅??????锟�?
????IStack<int> s1 = Stack<int>.Empty;
????IStack<int> s2 = s1.Push(10);
????IStack<int> s3 = s2.Push(20);
????IStack<int> s4 = s3.Push(30);
????IStack<int> v3 = s4.Pop();
????foreach (var item in s4)
????{
????//dosomething
????}
???????Push????????????????????????????????????????????????????????
????Net???????浼�??
???????????校???????斜??????????????????????????械????????Net??4.5?姹�??????????浼�????????? ???Nuget?????
????Install-Package Microsoft.Bcl.Immutable
??????????锟�?????????????????????????
????ImmutableStack<int> a1 = ImmutableStack<int>.Empty;
????ImmutableStack<int> a2 = a1.Push(10);
????ImmutableStack<int> a3 = a2.Push(20);
????ImmutableStack<int> a4 = a3.Push(30);
????ImmutableStack<int> iv3 = a4.Pop();
???????Net??????斜???????????????????????Push??????????????????????????push????????????????a1???????
????ImmutableStack<int> a1 = ImmutableStack<int>.Empty;
????a1.Push(10);
????//???????a1?????????push???????渭????
????a1 = a1.Push(10);
????//????????????????a1
????NET????????????
????ImmutableStack
????ImmutableQueue
????ImmutableList
????ImmutableHashSet
????ImmutableSortedSet
????ImmutableDictionary<K?? V>
????ImmutableSortedDictionary<K?? V>
????????浼�????浼�??????????????????