NULLCo
vertNodepHeadOfTreepLastNodeI
ListGettheheadofthedoubleli
kedlistBSTreeNodepHeadOfListpLastNodeI
ListwhilepHeadOfListpHeadOfListm_pLeftpHeadOfListpHeadOfListm_pLeftretur
pHeadOfList
f
02设计包含mi
函数的栈
题目:定义栈的数据结构,要求添加一个mi
函数,能够得到栈的最小元素。要求函数mi
、push以及pop的时间复杂度都是O1。分析:这是去年google的一道面试题。我看到这道题目时,第一反应就是每次push一个新元素时,将栈里所有逆序元素排序。这样栈顶元素将是最小元素。但由于不能保证最后push进栈的元素最先出栈,这种思路设计的数据结构已经不是一个栈了。在栈里添加一个成员变量存放最小元素(或最小元素的位置)。每次push一个新元素进栈的时候,如果该元素比当前的最小元素还要小,则更新最小元素。乍一看这样思路挺好的。但仔细一想,该思路存在一个重要的问题:如果当前最小元素被pop出去,如何才能得到下一个最小元素?因此仅仅只添加一个成员变量存放最小元素(或最小元素的位置)是不够的。我们需要一个辅助栈。每次push一个新元素的时候,同时将最小元素(或最小元素的位置。考虑到栈元素的类型可能是复杂的数据结构,用最小元素的位置将能减少空间消耗)push到辅助栈中;每次pop一个元素出栈的时候,同时pop辅助栈。参考代码:
i
cludedequei
cludeasserthtemplatetype
ameTclassCStackWithMi
publicCStackWithMi
voidvirtualCStackWithMi
voidTtopvoidco
stTtopvoidco
stvoidpushco
stTvaluevoidpopvoidco
stTmi
voidco
stprivateTm_datatheeleme
tsofstacksize_tm_mi
I
dexthei
dicesofmi
imumeleme
tsgetthelasteleme
tofmutablestack
ftemplatetype
ameTTCStackWithMi
Ttopretur
m_databackgetthelasteleme
tof
o
mutablestacktemplatetype
ameTco
stTCStackWithMi
Ttopco
stretur
m_databacki
serta
elme
tatthee
dofstacktemplatetype
ameTvoidCStackWithMi
Tpushco
stTvalueappe
dthedatai
tothee
dofm_datam_datapush_backvaluesetthei
dexofmi
imumelme
ti
m_dataatthee
dofm_mi
I
dexifm_mi
I
dexsize0m_mi
I
dexpush_back0elseifvaluem_datam_mi
I
dexbackm_mi
I
dexpush_backm_datasize1elsem_mi
I
dexpush_backm_mi
I
dexbackereasetheeleme
tatthee
dofstacktemplatetype
ameTvoidCStackWithMi
Tpoppopm_datam_datapop_backpopm_mi
I
dexm_mi
I
dexpop_backgetthemi
imumeleme
tofstacktemplatetype
ameTco
stTCStackWithMi
Tmi
co
stassertm_datasize0assertm_mi
I
dexsize0
fretur
m_datam_mi
I
dexback
举r