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;
        }
    };
    

      

  • 相关阅读:
    configure错误列表供参考
    php和AJAX用户注册演示程序
    php中文汉字截取函数
    阻止a标签点击跳转刷新
    js日期插件
    apache 开启Gzip网页压缩
    查询文章的上下篇Sql语句
    thinkphp简洁、美观、靠谱的分页类
    thinkphp自定义模板标签(二)
    thinkphp自定义模板标签(一)
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3626836.html
Copyright © 2011-2022 走看看