您的位置:首页 > 其它

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

2017-07-17 20:02 369 查看

在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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息