zoukankan      html  css  js  c++  java
  • 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.

    这题貌似见过,大概是编程之美之类吧。

    复习一下深拷贝和浅拷贝的区别:

    深拷贝保存了指针指向的内容,二浅拷贝应对指针指示给指针赋值。

    所以对于有指针的地方,浅拷贝非常不安全。

    这段代码用了2个栈,感觉很不效率,空间O(n)。

    有个空间O(1)的。

    /**
     * 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) {
            stack<RandomListNode *> sk;
            stack<RandomListNode *> sk2;
            if(head == NULL)return NULL;
            RandomListNode *temp = head;
            RandomListNode *cp = new RandomListNode (0);
            RandomListNode *cpp = cp;
            while(temp != NULL)
            {
                int val = temp->label;
                RandomListNode* node = new RandomListNode(val);
                cpp->next = node;
                cpp = node;
                sk.push(temp);
            
                temp = temp ->next;
                sk.top()->next = cpp;
            }
            while(! sk.empty())
            {
                temp =sk.top();
                if(temp->random != NULL)
                temp->next->random = temp->random->next;
                sk2.push(temp);
                sk.pop();
            }
            while(! sk2.empty())
            {
                temp = sk2.top();
                sk2.pop();
                if(sk2.empty())temp->next =NULL;
                else
                {
                    temp->next =sk2.top();
                }
            }
            return cp->next;
        }
    };
    

      

  • 相关阅读:
    szoj657 【AHSDFZNOI 7.2 WuHongxun】Odd
    cogs2652 秘术「天文密葬法」
    bzoj1026 [SCOI2009]windy数
    bzoj1862/1056: [Zjoi2006]GameZ游戏排名系统
    java-PreparedStatement的用法
    java-JDBC登录注册代码
    java-String Date Calendar之间的转换
    java-如何用eclipse打包jar
    java-通过JDBC操作数据库
    java-JDBC配置驱动程序
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3626836.html
Copyright © 2011-2022 走看看