面試題30 複雜鍊錶的複製

2021-07-09 04:03:34 字數 1485 閱讀 3176

題目:請實現函式complexlistnode* clone(complexlistnode* phead),複製乙個複雜鍊錶。在複製鍊錶中,每乙個結點除了有乙個m_pnext指標指向下乙個結點處,還有乙個m_psibling指向鍊錶中的任意結點或者null。

結點定義如下:

struct complexlistnode;
如果沒有那個任意指標,則可以按順序複製鍊錶就行了。

當然可以先複製next指標,時間複雜度o(n),再複製psibling指標,由於要查詢,重新定位,時間複雜度o(n^2)。

當然也可以先複製next指標,然後將原結點指標和新節點指標用map對應起來,這樣用o(n)的空間換來o(1)的查詢時間,最後的總時間複雜度為o(n)。

第一步:將複製的結點接在原結點的後面。

第二步:複製psibling。

第三步:將鍊錶分成兩個鍊錶。

#include #include #include #include #include #include using namespace std;

struct complexlistnode

};/*將鍊錶的每乙個結點複製,且接在原來結點的後面*/

void copynode(complexlistnode* head)

}/*複製psibling,新結點的psibling是前乙個結點psibling所指結點的下乙個結點*/

void copysibnode(complexlistnode* head)

}/*將鍊錶分成兩個鍊錶,返回新鍊錶的頭結點*/

complexlistnode* dividlist(complexlistnode* head)

return newhead;

}complexlistnode* clone(complexlistnode* phead)

void display(complexlistnode* a)

}int main()

下面補上利用hash table思想的**:

#include #include #include #include #include #include #include using namespace std;

struct complexlistnode

};complexlistnode* copynode(complexlistnode* phead, map&hash)

return newhead;

}void copysibnode(complexlistnode* phead, complexlistnode* nhead, map&hash)

}complexlistnode* clone(complexlistnode* phead)

void display(complexlistnode* a)

}int main()

面試題 複雜鍊錶複製

lettcode面試題35.複雜鍊錶的複製 請實現 copyrandomlist 函式,複製乙個複雜鍊錶。在複雜鍊錶中,每個節點除了有乙個 next 指標指向下乙個節點,還有乙個 random 指標指向鍊錶中的任意節點或者 null。class node int val node next node...

面試題 複雜鍊錶的複製

對於這個題,基本會有三個思路 1.這裡鍊錶的複製和單鏈表最大的不同,就是多了乙個自由指標 psub 那麼最簡單的想法就是,遍歷單鏈表,找到psub指向的節點,然後複製,這樣做最簡單,事件複雜度為o n的平方 2.基於第一種方法的優化,第一種方法把事件浪費在了查詢節點上,那麼我們可以建立乙個雜湊函式,...

面試題26 複雜鍊錶的複製

以下圖為5個結點的複雜鍊錶,實線表示m pnext指標的指向,虛線表示m psibling指標的指向 方法一 分兩步 1 遍歷一遍鍊錶,用m pnext指標將鍊錶連起來,o n 2 確定每個m psibling指標的指向,需重新遍歷新鍊錶確定其m psibling的指向,o n 時間代價為o n 2...