138. Copy List with Random Pointer【力扣】

题意理解

有一个链表,每个节点除了有指向下一个节点的指针外,还有一个随机的指针。深拷贝这个链表。

问题分析

用hashtable。

算法思路是进行两次遍历,第一次是走旧链表next指针拷贝所有节点,将旧节点地址和新节点地址建立映射;第二次是走新链表next指针利用映射表更新所有随机指针。

其他

链表遍历结构分两步:

1. 处理头结点

2.循环后续结点,循环条件是p->next(不是p),循环体第一句是p = p -> next

这样结构清晰不乱,有时候灵活反而花费较多的时间,定死一个效果会更好。

链接

Node* copyRandomList(Node* head) {
        if (!head) return NULL;    //空链表直接返回
        map<Node*, Node*> dict;    //新旧结点hash表
        
        Node* newHead = new Node(head -> val, head -> next, head -> random); //新结点复制旧结点
        Node* newP = newHead;    //保留新头结点
        dict[head] = newHead;    //保存新旧结点映射
        
        while(head -> next)    //遍历旧链表
        {
            head = head -> next;    //后移旧链表指针
            newP -> next = new Node(head -> val, head -> next, head -> random);    //复制旧链表结点到新链表
            newP = newP -> next;    //后移新链表指针
            dict[head] = newP;    //保存新旧结点映射
        }
        newP = newHead;    //重置新链表的指针
        newP -> random = dict[ newP -> random ];    //利用hash表修改新链表头随机指针
        while( newP -> next )    //遍历新链表
        {
            newP = newP -> next;    //后移指针
            newP -> random = dict[ newP -> random];    //修改新链表结点随机指针
        }
        return newHead;
    }

猜你喜欢

转载自blog.csdn.net/xiexie1357/article/details/88591547