栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

经典链表拷贝算法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

经典链表拷贝算法

问题描述:

  • rand指针是单链表节点结构中新增的指针,rand可能指向链表中的任意一个节点,也可能指向null,给定一个由Node节点组成的无环单链表的头节点head,实现链表的复制,并返回新链表的头节点。
  • 时间复杂度O(N),额外空间复杂度O(1)

链表结构:

class Node {
public:
    Node* next=NULL;
    Node* rand=NULL;
    int value;
    Node(int _value) {
        this->value = _value;
    }
};

实现方式:
1、通过节点的拷贝形成新的链表
代码实现:

Node* cur = head;
    Node* next = NULL;
    //构建克隆指针
    while (cur != NULL) {
        next = cur->next;
        cur->next = new Node(cur->value);
        cur->next->next = next;
        cur = next;
    }

2、构建rand指针
代码实现:

 cur = head;
    Node* nodeCopy = NULL;
    while (cur != NULL) {
        next = cur->next->next;
        nodeCopy = cur->next;
        nodeCopy->rand = cur->rand != NULL ? cur->rand->next : NULL;
        cur = next;
    }

3、拆分链表
代码实现:

 Node* res = head->next;
    cur = head;
    while (cur != NULL) {
        next = cur->next->next;
        nodeCopy = cur->next;
        cur->next = next;
        nodeCopy->next = next != NULL ? next->next : NULL;
        cur = next;
    }

全部实现代码如下:

Node* CopyNode(Node* head) {
    if (head == NULL) {
        return NULL;
    }
  
    Node* cur = head;
    Node* next = NULL;
    //构建克隆指针
    while (cur != NULL) {
        next = cur->next;
        cur->next = new Node(cur->value);
        cur->next->next = next;
        cur = next;
    }
    printNode(head);

    //构建rand
    cur = head;
    Node* nodeCopy = NULL;
    while (cur != NULL) {
        next = cur->next->next;
        nodeCopy = cur->next;
        nodeCopy->rand = cur->rand != NULL ? cur->rand->next : NULL;
        cur = next;
    }
    std::cout << "rand" << std::endl;
    printNode1(head);
    printNode1(head->next);

    //拆分链表
    Node* res = head->next;
    cur = head;
    while (cur != NULL) {
        next = cur->next->next;
        nodeCopy = cur->next;
        cur->next = next;
        nodeCopy->next = next != NULL ? next->next : NULL;
        cur = next;
    }
    printNode(res);

    DeleteNode(cur);
    DeleteNode(next);

    return res;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/666059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号