zoukankan      html  css  js  c++  java
  • leetcode[138]Copy List with Random Pointer

    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.

    /**
     * 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) {
            RandomListNode *p=head;
            RandomListNode *pnext=NULL;
            RandomListNode *tmp=NULL;
            while(p)
            {
                pnext=p->next;
                tmp=new RandomListNode(p->label);
                p->next=tmp;
                tmp->next=pnext;
                p=pnext;
            }
            p=head;
            while(p)
            {
                if(p->random)p->next->random=p->random->next;
                p=p->next->next;
            }
            RandomListNode *newhead=new RandomListNode(0);
            pnext=newhead;
            p=head;
            while(p)
            {
                pnext->next=p->next;
                pnext=pnext->next;
    //            if(pnext->next)p->next=pnext->next;
    //            else p->next=NULL;
                p->next=pnext->next;//
                p=p->next;
            }
            return newhead->next;
        }
    };
  • 相关阅读:
    HDU 1333 基础数论 暴力
    HDU 1299 基础数论 分解
    HDU 1211 EXGCD
    HDU 3507 单调队列 斜率优化
    博弈
    std:ios::sync_with_stdio(false);
    NBUT[1220] SPY
    nbut1217 Dinner
    poj2236Wireless Network
    ZOJ Problem Set
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281239.html
Copyright © 2011-2022 走看看