实现一个栈,属性Min返回最小值,操作的时间复杂度为o(1)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_34937637/article/details/81085153

题目:实现一个栈,要求实现出栈pop(),入栈push(),Min返回最小值的操作的时间复杂度为o(1);
思路:要使这些操作的时间复杂度为o(1),则必须保证栈的每个元素只被遍历一次

代码实现:

using System;
using System.Collections;
using System.Collections.Generic;

namespace cchoop
{
    class Program
    {
        static void Main(string[] args)
        {
            MyStack<int> myStack = new MyStack<int>((a, b) =>
            {
                if (a > b)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            });
            myStack.Push(3);
            myStack.Push(5);
            myStack.Push(2);
            myStack.Push(5);
            myStack.Push(2);
            myStack.Pop();
            myStack.Pop();
            myStack.Pop();
            Console.WriteLine("最小值为:" + myStack.Min);
            PrintCollection(myStack);
        }

        static void PrintCollection(IEnumerable collection)
        {
            foreach (var item in collection)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }
    }

    class MyStack<T> : IEnumerable<T>
    {
        private Stack<T> dataStack;
        private Stack<T> minStack;
        private Func<T, T, int> Compare;
        public T Min
        {
            get
            {
                return minStack.Peek();
            }
        }

        public MyStack(Func<T, T, int> compare)
        {
            this.Compare = compare;
            this.dataStack = new Stack<T>();
            this.minStack = new Stack<T>();
        }

        public T Pop()
        {
            T value = this.dataStack.Pop();
            if (value.Equals(minStack.Peek()))
            {
                minStack.Pop();
            }
            return value;
        }
        public void Push(T value)
        {
            if (minStack.Count == 0)
            {
                minStack.Push(value);
            }
            else if (Compare(value, minStack.Peek()) != 1)  //value小于或者等于最小值
            {
                minStack.Push(value);
            }

            this.dataStack.Push(value);
        }

        public IEnumerator<T> GetEnumerator()
        {
            return dataStack.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return dataStack.GetEnumerator();
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页