public StackMateItem(object p_minValue, int p_count, StackMateItem p_nextRef)
{
_minValue = p_minValue;
_count = p_count;
_nextRef = p_nextRef;
}
}
private StackMateItem _currStackMateItem = null;
public StackEx() : base()
{
_currStackMateItem = new StackMateItem();
}
public override object Pop()
{
object obj = base.Pop();
if (obj != null && _currStackMateItem.MinValue != null)
{
if (obj == _currStackMateItem.MinValue)
{
int valueCount = _currStackMateItem.DecCount();
if (valueCount == 0)
{
_currStackMateItem = _currStackMateItem.NextRef;
}
}
}
return obj;
}
public override void Push(object obj)
{
if (!(obj is IComparable))
{
throw new InvalidCastException();
}
base.Push(obj);
if (_currStackMateItem.MinValue == null)
{
_currStackMateItem.MinValue = obj;
_currStackMateItem.AddCount();
}
else if (_currStackMateItem.MinValue == obj)
{
_currStackMateItem.AddCount();
}
else if ((_currStackMateItem.MinValue as IComparable).CompareTo(obj) > 0)
{
StackMateItem minItem = new StackMateItem();
minItem.MinValue = obj;
minItem.AddCount();
minItem.NextRef = _currStackMateItem;
_currStackMateItem = minItem;
}
}
/// <summary>
/// 堆栈最小值。
/// </summary>
public object Min
{
get
{
if (_currStackMateItem == null)
{
throw new NullReferenceException();
}
return _currStackMateItem.MinValue;
}
}
private static void TestStackEx()
{
StackEx myStackEx = new StackEx();
System.Random myRand = new System.Random();
Console.WriteLine("<<PUSH IN>>");
for (int k = 0; k < 11; k++)
{
myStackEx.Push(myRand.Next(1, 10));
PrintValues(myStackEx, ' ');
}
Console.WriteLine("<<POP OUT>>");
while (myStackEx.Count > 0)
{
myStackEx.Pop();
PrintValues(myStackEx, ' ');
}
}
public static void PrintValues( StackEx myStackEx, char mySeparator )
{
if (myStackEx == null || myStackEx.Count < 1)
{
return;
}
Array myArr = myStackEx.ToArray();
System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
int i = 0;
int cols = myArr.GetLength( myArr.Rank - 1 );
Console.Write("Stack:");
while ( myEnumerator.MoveNext())
{
if ( i < cols )
{
i++;
}
else
{
Console.WriteLine();
i = 1;
}
Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
}
Console.WriteLine();
Console.Write("MinVal:" + myStackEx.Min);
Console.WriteLine();
}
public static void Main()
{
TestStackEx();
RL();
}