Copy a linked list

前端 未结 3 1526
南方客
南方客 2021-01-01 19:48
typedef struct Node
{
  int data;
  Node *next;
  Node *other;
};

Node *pHead;

pHead is a singly linked list. The next f

3条回答
  •  清歌不尽
    2021-01-01 20:14

    Create a new node for every node in the old list, copy the corresponding data and make the next pointer of the nodes in the new list point to their successor in the new list, forgetting the other pointer for time being. At the time of creating a new node remember the mapping of node address something like:

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

    In the second pass pass for every node in the new list consider its other pointer and find its corresponding node in the new list from the map and use it as the other pointer of this node (node in the new list).

提交回复
热议问题