劍指offer面試題21

2021-06-22 07:52:02 字數 1410 閱讀 6207

面試題21:包含min函式的棧

題目:定義棧的資料結構,請在該型別中實現乙個能夠得到棧的最小元素的min函式。在該棧中,呼叫min、push及pop的時間複雜度都是o(1).

預備知識:

棧的定義:

模板函式:

思路:面對乙個複雜的問題,我們可以舉幾個具體的例子來尋找規律,對於本題目,我們可以通過舉例來分析它。

演算法實現:

stackwithmin.h

#pragma once

#include //stl中stack 棧

#include template class stackwithmin

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::stackm_data; // 資料棧,存放棧的所有元素

std::stackm_min; // 輔助棧,存放棧的最小元素

};/**********************成員函式的實現******************/

//壓入

template void stackwithmin::push(const t& value)

template void stackwithmin::pop()

template const t& stackwithmin::min() const

template t& stackwithmin::top()

template const t& stackwithmin::top() const

template bool stackwithmin::empty() const

template size_t stackwithmin::size() const

main.cpp

// 面試題21.cpp : 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include "stackwithmin.h"

//包含min函式的棧

void test(char* testname, const stackwithmin& stack, int expected)

int _tmain(int argc, _tchar* argv)

注意事項:

劍指offer 面試題21 相關

題目 設計包含min函式的棧,pop push min 的時間複雜度均為o 1 自己所寫 如下 寫 棧 的 還是有些不熟練!include using namespace std const int max 100 class stack stack stack stack stack bool s...

劍指offer面試題7

面試題7 用兩個棧實現佇列 using namespace std template class cqueue 預備知識 佇列 佇列也是一種常見的資料結構 特點是先進先出 fifo 在stl中有stack和queue兩個容器 template class stack 成員函式 empty size ...

劍指offer面試題11

面試題1 數值的整數的次方 題目 實現函式double power double base,int exponent 求base的 exponent次方。不得使用庫函式,同時不需要考慮大數問題。思路 首先應該明確指數的可能取值 正整數,0,負整數 另外還需要考慮底數是0的情形。對於負整指數,我們可以...