复杂链表的复制

来源:互联网 发布:rip的udp端口号是 编辑:程序博客网 时间:2024/06/04 19:41

复杂链表:除了有一个指向下一个节点的next指针外,还有一个指向随机节点的random指针

typedef int DataType;typedef struct ComplexNode{     DataType _data; // 数据     struct ComplexNode * _next; // 指向下一个节点的指针     struct ComplexNode * _random; // 指向随机节点(可以是链表中的任意节点 or 空)}ComplexNode,*pComplexNode;pComplexNode CreateComplexNode(DataType d){     pComplexNode newNode = (pComplexNode)malloc(sizeof(ComplexNode));     if (newNode == NULL)     {          perror("malloc");          return NULL;     }     newNode->_data = d;     newNode->_next = NULL;     newNode->_random = NULL;}pComplexNode ChoneComplexlist(pComplexNode head){     pComplexNode cur = head;     pComplexNode tmp = NULL;     pComplexNode copy = NULL;     pComplexNode tail = NULL;     while (cur)     {          pComplexNode newNode = CreateComplexNode(cur->_data);          tmp = cur;          cur = cur->_next;          newNode->_next = cur;          tmp->_next = newNode;     }     cur = head;     while (cur)     {          cur->_next->_random = cur->_random->_next;          cur = cur->_next->_next;     }     cur = head;     copy = cur->_next;     tail = copy;     while (tail->_next)     {          tail->_next = tail->_next->_next;          cur->_next = tail->_next;          cur = cur->_next;          tail = tail->_next;     }     cur->_next = NULL;     return copy;}