簡體   English   中英

復制鏈接列表

[英]Copy a linked list

typedef struct Node
{
  int data;
  Node *next;
  Node *other;
};

Node *pHead;

pHead是一個單獨鏈表。 next字段指向列表中的下一個元素。 other字段可以指向列表中的任何其他元素(可以是前一個節點之一或前面的一個節點)或NULL

如何編寫復制鏈接列表及其連接的復制功能? 新列表中的所有元素( nextother元素)都不應指向舊列表中的任何元素。

為舊列表中的每個節點創建一個新節點,復制相應的數據,並使新列表中節點的下一個指針指向新列表中的后繼節點,暫時忘記other指針。 在創建新節點時,請記住節點地址的映射,例如:

Old_list   New_list
------------------- 
0x123      0x345     [ addresses of the first node]
0xabc      0xdef     [ addresses of the second node]
...

在新列表中的每個節點的第二次傳遞中,考慮其other指針,並從映射中的新列表中找到其對應的節點,並將其用作此節點的other指針(新列表中的節點)。

碰到了這個 希望能幫助到你!

引用此鏈接中的一個解決方案,如下所示。

1)創建1的副本並將其插入1和2之間,創建2的副本並將其插入2和3之間。以這種方式繼續,將N的副本添加到第N個節點

2)現在以這種方式復制任意鏈接

 if original->arbitrary is not NULL
   original->next->arbitrary = original->arbitrary->next;  /*TRAVERSE TWO NODES*/
 else
   original->next->arbitrary=NULL;

這是有效的,因為原始 - >接下來只是原始副本和原始 - >任意 - >接下來只是任意副本。

3)現在以這種方式在單個循環中恢復原始和復制鏈接列表。

 original->next = original->next->next;
 copy->next = copy->next->next;

4)確保original-> next的最后一個元素為NULL。

示例代碼,時間復雜度O(N),空間復雜度O(1)

pNode copy_list(pNode head) {
  // pre-condition: node->other either points into the list or NULL
  if (!head) return NULL;

  pNode node = head, copied = NULL, cnode = NULL;
  for ( ; node; node = node->next->next) {
    // make copy
    cnode = newnode(node->next, node->data);
    cnode->other = node->other;
    if (node == head)
      copied = cnode;

    // insert the copy between originals    
    node->next = cnode;    
    // node -> cnode -> (orig)node->next
  }

  for (node = head; node && node->next; 
       node = node->next->next /* only original nodes */) 
    if (node->other)
      node->next->other = node->other->next;
    else
      node->next->other = NULL;    

  // restore lists
  node = head; cnode = copied;
  for ( ; cnode && cnode->next; node = node->next, cnode = cnode->next) { 
    node->next = node->next->next;
    cnode->next = cnode->next->next;
  }
  node->next = NULL;
  return copied;
}

完整的計划見http://gist.github.com/349630

我喜歡Codaddict的解決方案,但這將是我的答案:

  1. 迭代鏈表。
    一個。 將數據存儲在一個數組中(當然,第i個節點的位置i)
    用i替換數據來創建一個id(這樣你肯定知道你在說哪個節點)

  2. 創建第一個大小的第二個鏈表(暫時忽略其他指針)*。 也許使用臨時數組來快速找到每個節點

  3. 迭代第一個鏈表。 一個。 找出其他點的id(在該節點數據中)b。 在第二個鏈接列表中重新創建此鏈接(臨時數組可能真的有幫助)

  4. 同時迭代兩個鏈表並用存儲的數據替換數據中的ID

當然你可以在這里崩潰一些處理和迭代。 但這大致是我想要做的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM