zoukankan      html  css  js  c++  java
  • 【leetcode】Copy List with Random Pointer (hard)

    A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

    Return a deep copy of the list.

    思路:

    做过,先复制一遍指针,再复制random位置,再拆分两个链表。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <queue>
    #include <stack>
    using namespace std;
    
    
    // Definition for singly-linked list with a random pointer.
    struct RandomListNode {
        int label;
        RandomListNode *next, *random;
        RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
    };
     
    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            if(head == NULL) return NULL;
    
            RandomListNode * p = head;
    
            //在每个结点后面复制一个自己 不管random指针
            while(p != NULL)
            {
                RandomListNode * cpy = new RandomListNode(p->label);
                cpy->next = p->next;
                p->next = cpy;
    
                p = cpy->next;
            }
    
            //复制random指针
            p = head;
            while(p != NULL)
            {
                RandomListNode * cpy = p->next;
                if(p->random != NULL)
                {
                    cpy->random = p->random->next;
                }
    
                p = cpy->next;
            }
    
            //把原链表与复制链表拆开
            RandomListNode * cpyhead = head->next;
            p = head;
            RandomListNode * cpy = cpyhead;
            while(p != NULL)
            {
                p->next = cpy->next;
                cpy->next = (cpy->next == NULL) ? cpy->next : cpy->next->next;
    
                p = p->next;
                cpy = cpy->next;
            }
    
            return cpyhead;
        }
    };
    
    int main()
    {
        RandomListNode * r = new RandomListNode(-1);
        Solution s;
        RandomListNode * ans = s.copyRandomList(r);
    
        return 0;
    }
  • 相关阅读:
    STM8s窗口看门狗
    开篇
    习题6-8 统计一行文本的单词个数
    习题9-4 查找书籍
    习题9-3 平面向量加法
    习题9-1 时间换算
    习题7-8 字符串转换成十进制整数
    习题8-10 输出学生成绩
    习题7-7 字符串替换
    习题7-6 统计大写辅音字母
  • 原文地址:https://www.cnblogs.com/dplearning/p/4311731.html
Copyright © 2011-2022 走看看