JD2022-TU1/main/tools/framework/JD.Collections/LinkedListStack.cs

120 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using JD.Collections.Immutable;
namespace JD.Collections
{
/// <summary>
/// A stack implemented using a singly-linked list, allowing for easy and fast shallow cloning.
/// </summary>
public sealed class LinkedListStack<T> : IEnumerable<T>, ICloneable
{
#region Variables
private ImmutableStack<T> m_top = new ImmutableStack<T>();
#endregion
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
public LinkedListStack()
{
}
private LinkedListStack(LinkedListStack<T> other)
{
m_top = other.m_top;
}
#endregion
#region Properties
/// <summary>
/// Returns true if the <see cref="LinkedListStack{T}"/> is empty.
/// </summary>
public bool IsEmpty
{
get
{
return m_top.IsEmpty;
}
}
#endregion
#region Methods
/// <summary>
/// Inserts an object at the top of the <see cref="LinkedListStack{T}"/>.
/// </summary>
/// <remarks>
/// This method is an O(1) operation.
/// </remarks>
/// <param name="value">The object to push onto the <see cref="LinkedListStack{T}"/>. The value can be a null reference for reference types.</param>
public void Push(T value)
{
m_top = m_top.Push(value);
}
/// <summary>
/// Removes and returns the object at the top of the <see cref="LinkedListStack{T}"/>.
/// </summary>
/// <remarks>
/// This method is similar to the <see cref="Peek"/> method, but <see cref="Peek"/> does not modify the <see cref="LinkedListStack{T}"/>.
/// This method is an O(1) operation.
/// </remarks>
/// <returns>The object removed from the top of the <see cref="LinkedListStack{T}"/>.</returns>
public T Pop()
{
T current = m_top.Peek();
m_top = m_top.Pop();
return current;
}
/// <summary>
/// Returns the object at the top of the <see cref="LinkedListStack{T}"/> without removing it.
/// </summary>
/// <remarks>
/// This method is similar to the <see cref="Pop"/> method, but <see cref="Peek"/> does not modify the <see cref="LinkedListStack{T}"/>.
/// This method is an O(1) operation.
/// </remarks>
/// <returns>The object at the top of the <see cref="LinkedListStack{T}"/>.</returns>
/// <exception cref="InvalidOperationException">The Stack is empty.</exception>
public T Peek()
{
return m_top.Peek();
}
/// <summary>
/// Clones the current stack.
/// </summary>
/// <returns></returns>
public LinkedListStack<T> Clone()
{
return new LinkedListStack<T>(this);
}
object ICloneable.Clone()
{
return Clone();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return m_top.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
#endregion
}
}