1. 程式人生 > >[劍指offer] 25. 復雜鏈表的復制

[劍指offer] 25. 復雜鏈表的復制

label 映射關系 利用 bsp 解決 span 一起 以及 return

題目描述

輸入一個復雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果為復制後復雜鏈表的head。(註意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
思路: 因為新鏈表也需要復制舊鏈表的random指針,而random指向的節點也有其next和random,需要保持鏈表的連貫,所以需要考慮先做出一條新鏈表,再去構建每一個節點的random節點,而如何同步random節點就是問題所在。有兩種解決辦法。 解法一:構建同一鏈表後拆分 1.新舊鏈表構建在一起,形成Z字型 2.為每一個新節點同步random節點 3.分開兩個鏈表
class
Solution { public: RandomListNode *Clone(RandomListNode *pHead) { if (pHead == NULL) return NULL; RandomListNode *newHead = new RandomListNode(pHead->label); RandomListNode *curNode1 = pHead; RandomListNode *curNode2 = newHead; // 新舊鏈表形成Z鏈 while (curNode1) { curNode2
->next = curNode1->next; curNode1->next = curNode2; curNode1 = curNode2->next; curNode2 = curNode1 == NULL ? NULL : new RandomListNode(curNode1->label); } curNode1 = pHead; curNode2 = newHead; // 新鏈添加random while (curNode1) { curNode2->random = curNode1->random == NULL ? NULL : curNode1->random->next; curNode1
= curNode2->next; curNode2 = curNode1 == NULL ? NULL : curNode1->next; } curNode1 = pHead; curNode2 = newHead; // 脫鏈 while (curNode1) { curNode1->next = curNode2->next; curNode2->next = curNode1->next == NULL ? NULL : curNode1->next->next; curNode1 = curNode1->next; curNode2 = curNode2->next; } return newHead; } };

解法二:利用哈希表

先構建新鏈表(label,next),同時哈希表存儲(舊鏈表節點,新鏈表節點)映射關系

再遍歷一遍舊鏈表,利用哈希的映射為新鏈表random賦值,oldNode->random = hash[newNode->random]

class Solution
{
public:
  RandomListNode *Clone(RandomListNode *pHead)
  {
    if (pHead == NULL)
      return NULL;

    map<RandomListNode *, RandomListNode *> m;
    RandomListNode *curNode1 = pHead;
    RandomListNode *curNode2 = new RandomListNode(curNode1->label);
    RandomListNode *newHead = curNode2;
    m[curNode1] = curNode2;
    while (curNode1)
    {
      curNode2->next = curNode1->next == NULL ? NULL : new RandomListNode(curNode1->next->label);
      curNode1 = curNode1->next;
      curNode2 = curNode2->next;
      m[curNode1] = curNode2;
    }

    curNode1 = pHead;
    curNode2 = newHead;
    while (curNode1)
    {
      curNode2->random = m[curNode1->random];
      curNode1 = curNode1->next;
      curNode2 = curNode2->next;
    }
    return newHead;
  }
};

[劍指offer] 25. 復雜鏈表的復制