链表深拷贝

链表深拷贝
假设有如下一个链表:

struct Node
{
int value ;
struct Node *next ;
struct Node *random ;
}
其中,random指向该链表的任意一个节点或者NULL,请编程实现该链表的深拷贝。

Node *deepCopy (Node *head)

/*
 * 程序用来复制一个复杂链表
 * 复杂链表表示:存在2个指针,一个指针之后下一个节点,另外一个随机指针指向随机节点
 * 分成3步:
 * 1. 复制节点,如A-B-C 变成 A-A’-B-B’-C-C’
 * 2. 依次遍历节点A,B,C,将这些节点的随机指针与A’B’C’一致
 * 3. 分离A-B-C和A’B’C’,A’B’C’便是需要求得链表
 * */
//step1. add same node to nodes in list
//step2. init the random pointer
//step3. split the list to two parts, return newNode

Node *deepCopy (Node *head) {
                    Node *p = head, *q = head->next, *newNode = NULL;

    //step 1
    while (p != NULL) {    
        newNode = (Node *)malloc(sizeof(Node));
        newNode->next = p->next;
        p->next = newNode;
        newNode->value = p->value;
        newNode->random = NULL;

        p = q;
        q = q->next;
    }

    //step 2
    p = head;
    q = p->next;
    while (q != NULL) {
        if (p->random != NULL)
            q->random = p->random->next;
        if (q->next == NULL)
            break;
        p = q->next;
        q = p->next;
    }  //step 3
    newNode = head->next;
    p = head; q = p->next;
    while (q != NULL) {
        p->next = q->next;
        if (q->next == NULL)
            break;
        q->next = p->next->next;

        p = p->next;
        q = q->next;
    }
    return newNode;
}

你可能感兴趣的:(编程)