剑指off-复制复杂链表

来源:互联网 发布:java web小项目下载 编辑:程序博客网 时间:2024/05/16 10:32

题目:链表的结构中多了一个spring指针,这个指针可能指向链表中的任何一个节点,复制这个复杂链表。

分析:首先想到的是第一种方法,复制next串联起来的链表,然后复制spring 指针,但是每次都要从头顺序查找spring指针在副本中的值,那么这个效率应该是O(n^2)

第二种方法是将副本建立在原来的链表中,在每一个原node后面新建我们的node,因为这还算一个链表,那么在复制spring指针的时候,只需要顺序一次,每次都是指向spring->next,最后最一次分割,next=nex->next;

struct complexnode{    int key;    complexnode* next;    complexnode* spring;};//第一步复制void clone(complexnode* pNode){    complexnode* pHead=pNode;    if(pHead==NULL)        return ;    while (pHead!=NULL) {        complexnode* newnode=new complexnode();        newnode->key=pHead->key;        newnode->next=pHead->next;        newnode->spring=NULL;        pHead->next=newnode;        pHead=newnode->next;    }}//第二步复制springvoid clonespring(complexnode* pHead){    complexnode* pNode=pHead;    complexnode* pNodeClone=pHead->next;    if (pNode == NULL || pNodeClone==NULL) {        printf("链表为空");        return ;    }    while (pNodeClone!=NULL) {        pNodeClone->spring=pNode->spring;        pNode=pNodeClone->next;        if (pNodeClone->next==NULL) {            return ;        }        pNodeClone=pNodeClone->next->next;    }}//第三步分解两个complexnode *reseolve(complexnode* pHead){    int a,b;    complexnode *pNode=pHead;    complexnode *pNodeClone=pHead->next;    complexnode *pNodeCloneHead=pHead->next; //用来返回        if (pNode == NULL || pNodeClone==NULL) {        printf("链表为空");        return  NULL;    }    while (pNodeClone!=NULL) {                if (pNodeClone->next==NULL) {            pNode->next=NULL;            return NULL;        }        pNode->next=pNodeClone->next;        pNode=pNode->next;        pNodeClone->next=pNode->next;        pNodeClone=pNodeClone->next;          }    printfclone(pNodeCloneHead);    return pNodeCloneHead;}


0 0