1. 程式人生 > >copy-list-with-random-pointer

copy-list-with-random-pointer


title: copy-list-with-random-pointer
date: 2018-12-09 00:27:33
categories: LeetCode
tags:[List]

描述:

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.

思想:

參考這個連結

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:
    RandomListNode *copyRandomList(RandomListNode *
head) { if(head == NULL) return head; //第一遍掃描,把複製出來的新節點插在原節點之後 RandomListNode* node = head; while(node != NULL) { RandomListNode* tmp = new RandomListNode(node->label); tmp->next = node->next; node->next =
tmp; node = node->next->next; } //第二遍掃描,根據原節點的random,給新節點的random賦值 node = head; while(node!=NULL) { if(node->random != NULL) node->next->random = node->random->next; node = node->next->next;//肯定是偶數個,並且node都指在奇數位置,所以while這樣判斷就好 } RandomListNode* newhead = head->next; //第三遍掃描,把新節點從圓臉點拆分出來 node = head; while(node != NULL) { RandomListNode* tmp = node->next; node->next = tmp->next; if(tmp->next != NULL) tmp->next = tmp->next->next; node = node->next; } return newhead; } };

Java程式碼:

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)
            return head;
        
        //在原節點後邊插入新建的節點
        RandomListNode p = head;
        while(p != null){
            RandomListNode tmp = new RandomListNode(p.label);
            tmp.next = p.next;
            p.next = tmp;
            p = tmp.next;
        }
        
        //按照原節點的random順序,建立新節點的random順序
        p = head;
        while(p != null){
            if(p.random != null){
                p.next.random = p.random.next;
            }
            p = p.next.next;
        }
        
        //從我們新建的這個連結串列中,把我們需要的摘出來
        RandomListNode newnode = head.next;
        p = head;
        while(p != null){
            RandomListNode tmp = p.next;
            p.next = tmp.next;
            if(tmp.next != null)
                tmp.next = tmp.next.next;
            p = p.next;
        }
        
        return newnode;
    }
}