劍指Offer面試題37

2021-07-24 17:29:21 字數 753 閱讀 7395

這題的難點在於理解單鏈表中如果有第乙個公共節點,那麼其後的所有節點都重合。

/*

public class listnode

}*/public

class solution

//記錄它們的長度可以不用兩個輔助棧,讓長的先走,可以同時到鏈尾

int nlen1 = getlistlength(phead1);

int nlen2 = getlistlength(phead2);

int nlendif = nlen1 - nlen2;

//不妨假定phead1較長

listnode plistheadlong = phead1;

listnode plistheadshort = phead2;

if(nlen2 > nlen2)

//先在長鍊表上走幾步,再同時在兩個鍊錶上遍歷

for(int i = 0; i < nlendif; i ++)

while((plistheadlong != null) && (plistheadshort != null)

&& (plistheadlong != plistheadshort))

//得到第乙個公共結點

return plistheadlong;

}private

intgetlistlength(listnode phead)

return nlen;

}}

劍指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的情形。對於負整指數,我們可以...

劍指offer面試題15

面試題15 鍊錶中倒數第k個結點 題目 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。為了符合大多數人的習慣,本題從1開始計數,即鍊錶的尾結點是倒數第乙個結點。例如乙個鍊錶有6個結點,從頭結點開始它們的值依次是1 2 3 4 5 6。這個鍊錶的倒數第3個結點是值為4的結點。預備知識 鍊錶結點的定義如下 ...