Copy a linked list

前端 未结 3 1523
南方客
南方客 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:19

    I like the solution of Codaddict, but this would be my answer:

    1. iterate over the linked list.
      a. store the data in an array (position i for the i'th node of course)
      b. replace data with i to create an id (this way you'll definitely know which node you are talking about)

    2. create the 2nd linked list the size of the first (ignore the other pointer for now) *. maybe use a temporary array to find each node quickly

    3. iterate over the first linked list. a. find out which id other points to (which is in that nodes data) b. recreate this link in the 2nd linked list (the temporary array could really help here)

    4. iterate over both linked list simultaneously and replace the ids in data with the stored data

    Of course you could collapse some processing and iterating here. But this would roughly be what I would do/think of.

提交回复
热议问题