关闭

【面试题二十一】包含min函数的栈

508人阅读 评论(0) 收藏 举报
分类:

包含min函数的栈

MinStack.cpp:

#include <iostream>
#include "StackWithMin.h"
#include <cstdio>

using namespace std;

void Test(char* testName, const StackWithMin<int>& stack, int expected)
{
    if(testName != NULL)
        printf("%s begins: ", testName);

    if(stack.min() == expected)
        printf("Passed.\n");
    else
        printf("Failed.\n");
}

int main()
{
    StackWithMin<int> stack;

    stack.push(3);
    Test("Test1", stack, 3);

    stack.push(4);
    Test("Test2", stack, 3);

    stack.push(2);
    Test("Test3", stack, 2);

    stack.push(3);
    Test("Test4", stack, 2);

    stack.pop();
    Test("Test5", stack, 2);

    stack.pop();
    Test("Test6", stack, 3);

    stack.pop();
    Test("Test7", stack, 3);

    stack.push(0);
    Test("Test8", stack, 0);

    return 0;
}



StackWithMin.cpp:

#include "StackWithMin.h"


StackWithMin.h:

#ifndef _STACK_WITH_MIN_H_
#define _STACK_WITH_MIN_H_

#include <stack>
#include <assert.h>
#include <stddef.h>

template <typename T> class StackWithMin
{
public:
    StackWithMin(void) {}
    virtual ~StackWithMin(void) {}

    T& top(void);
    const T& top(void) const;

    void push(const T& value);
    void pop(void);

    const T& min(void) const;

    bool empty() const;
    size_t size() const;

private:
    std::stack<T>   m_data;     // 数据栈,存放栈的所有元素
    std::stack<T>   m_min;      // 辅助栈,存放栈的最小元素
};

template <typename T> void StackWithMin<T>::push(const T& value)
{
    // 把新元素添加到辅助栈
    m_data.push(value);

    // 当新元素比之前的最小元素小时,把新元素插入辅助栈里;
    // 否则把之前的最小元素重复插入辅助栈里
    if(m_min.size() == 0 || value < m_min.top())
        m_min.push(value);
    else
        m_min.push(m_min.top());
}

template <typename T> void StackWithMin<T>::pop()
{
    assert(m_data.size() > 0 && m_min.size() > 0);

    m_data.pop();
    m_min.pop();
}


template <typename T> const T& StackWithMin<T>::min() const
{
    assert(m_data.size() > 0 && m_min.size() > 0);

    return m_min.top();
}

template <typename T> T& StackWithMin<T>::top()
{
    return m_data.top();
}

template <typename T> const T& StackWithMin<T>::top() const
{
    return m_data.top();
}

template <typename T> bool StackWithMin<T>::empty() const
{
    return m_data.empty();
}

template <typename T> size_t StackWithMin<T>::size() const
{
    return m_data.size();
}


#endif /*_STACK_WITH_MIN_H_*/


Makefile:

.PHONY:clean
CPP=g++
CFLAGS=-Wall -g
BIN=test
OBJS=MinStack.o StackWithMin.o
LIBS=
$(BIN):$(OBJS)
	$(CPP) $(CFLAGS) $^ -o $@ $(LIBS)
%.o:%.cpp
	$(CPP) $(CFLAGS) -c $< -o $@
clean:
	rm -f *.o $(BIN)
运行结果:

Test1 begins: Passed.
Test2 begins: Passed.
Test3 begins: Passed.
Test4 begins: Passed.
Test5 begins: Passed.
Test6 begins: Passed.
Test7 begins: Passed.
Test8 begins: Passed.


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:48910次
    • 积分:917
    • 等级:
    • 排名:千里之外
    • 原创:44篇
    • 转载:1篇
    • 译文:0篇
    • 评论:2条
    博客专栏
    文章分类
    最新评论