/// <summary> /// Remove and return the first value in the stack (LIFO). /// If the stack is empty, default value is returned. /// Time: O(1). /// </summary> /// <returns>The first value in the stack, or default if it's empty</returns> public ValueType Pop() { if (null == StackRoot) { return(default(ValueType)); } ValueType value = StackRoot.Value; StackRoot = StackRoot.Next; StackMaxRoot = StackMaxRoot.Next; return(value); }
/// <summary> /// Insert the value on top of the stack. /// Time: O(1). /// </summary> /// <param name="value"></param> public void Push(ValueType value) { LinkedNode <ValueType> valueNode = new LinkedNode <ValueType>(value); if (null == StackRoot) { StackRoot = valueNode; StackMaxRoot = new LinkedNode <ValueType>(value); } else { // push nello stack valueNode.Next = StackRoot; StackRoot = valueNode; // aggiornamento max ValueType max = (value.CompareTo(StackMaxRoot.Value) >= 0) ? value : StackMaxRoot.Value; LinkedNode <ValueType> maxNode = new LinkedNode <ValueType>(max); maxNode.Next = StackMaxRoot; StackMaxRoot = maxNode; } }
public LinkedNode(ValueType value) { Value = value; Next = null; }
public MaxStack() { StackRoot = null; StackMaxRoot = null; }