zoukankan      html  css  js  c++  java
  • LintCode

    LintCode - Copy List with Random Pointer

    http://www.lintcode.com/en/problem/copy-list-with-random-pointer/

    Description

    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.
    - Challenge
    Could you solve it with O(1) space?

    Code - C++

    /**
     * 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:
        /**
         * @param head: The head of linked list with a random pointer.
         * @return: A new head of a deep copy of the list.
         */
        void copyNext(RandomListNode* head) {
            while (head != NULL) {
                RandomListNode* newNode = new RandomListNode(head->label);
                newNode->random = head->random;
                newNode->next = head->next;
                head->next = newNode;
                head = head->next->next;
            }
        }
        void copyRandom(RandomListNode* head) {
            while (head != NULL) {
                if (head->next->random != NULL) {
                    head->next->random = head->random->next;
                }
                head = head->next->next;
            }
        }
        RandomListNode* splitList(RandomListNode* head) {
            RandomListNode* newHead = head->next;
            while (head != NULL) {
                RandomListNode* temp = head->next;
                head->next = temp->next;
                head = head->next;
                if (temp->next != NULL) {
                    temp->next = head->next;
                }
            }
            return newHead;
        }
        RandomListNode *copyRandomList(RandomListNode *head) {
            // write your code here
            if (head == NULL) {
                return NULL;
            }
            copyNext(head);
            copyRandom(head);
            return splitList(head);
        }
    };

    Tips:

    • None
  • 相关阅读:
    js 词法作用域揭秘
    Python 操作 Redis 发布订阅
    Logistic Regression
    快速逆平方根
    牛顿法
    Ubuntu安装BCC
    树莓派4b安装Ubuntu20.04
    丢弃法
    SpringBoot整合Redis
    Linear Regression
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/7345371.html
Copyright © 2011-2022 走看看