O(1)时间复杂度删除链表节点/复制带随机指针的链表

在O(1)时间复杂度删除链表节点

直接将需要删除节点的写一个节点的val直接赋值给需删除节点,然后删除他的next即可

class Solution {
public:
    /**
     * @param node: a node in the list should be deleted
     * @return: nothing
     */
    void deleteNode(ListNode *node) {
        // write your code here
        if(node==NULL)
            return;

        ListNode* cur=node->next;
        node->val=cur->val;
        node->next=cur->next;
        delete cur;

    }
};

复制带随机指针的链表

这里用unordered_map来做,另外一种方法网上都有,随便一搜一大堆。
容器中存着节点

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.
     */
    RandomListNode *copyRandomList(RandomListNode *head) {
        // write your code here
        if(head==NULL)
            return head;
    unordered_map<RandomListNode*, RandomListNode*> hashmap;
    RandomListNode* cur=head;
    while (cur != NULL)
    {
        hashmap.insert(make_pair(cur, new RandomListNode(cur->label)));
        cur = cur->next;
    }
    cur=head;
    for (; cur != NULL; cur=cur->next)
    {
        hashmap[cur]->next = hashmap[cur->next];
        hashmap[cur]->random = hashmap[cur->random];
    }
     return hashmap[head];   
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值