复杂链表的复制

 题目:有一个复杂链表,其结点除了有一个 m_pNext 指针指向下一个结点外,还有一个 m_pSibling 指向链表中的任一结点或者 NULL 。其结点的 C++ 定义如下:

                struct ComplexNode

{

    int m_nValue;

    ComplexNode* m_pNext;

    ComplexNode* m_pSibling;

};

                下图是一个含有5个结点的该类型复杂链表。图中实线箭头表示m_pNext指针,虚线箭头表示m_pSibling指针。为简单起见,指向NULL的指针没有画出。

 

                  程序员面试题精选100题(49)-复杂链表的复制 - 何海涛 - 微软、Google等面试题  

                

请完成函数ComplexNode* Clone(ComplexNode* pHead),以复制一个复杂链表。

 

 

struct ComplexNode {
  ComplexNode* next;
  ComplexNode* random;
  int value;
};

void CloneNext(ComplexNode* origin) {
  if (NULL == origin) {
    return;
  }
  ComplexNode* current = origin;
  while (current) {
    ComplexNode* temp = new ComplexNode();
    temp->value = current->value;
    temp->random = NULL:
    temp->next = current->next;
    current->next = temp;
    current = temp->next;
  }
}

void CloneRandom(ComplexNode* origin) {
  if (NULL == origin) {
    return;
  }
  ComplexNode* current = origin;
  ComplexNode* clone = NULL;

  while (current) {
    clone = current->next;
    if (current->random) {
      clone->random = current->random->next;
    }
    current = clone->next;
  }

}


ComplexNode* Clone(ComplexNode* origin) {
  ComplexNode* clone_head = NULL;    
  ComplexNode* clone_node = NULL;    
  ComplexNode* node = origin;    
  if (node) {
    clone_head = node->next;
    clone_node = node->next;
  }
  while (node) {
    node->next = clone_node->next;
    node = node->next;
    clone_node->next = node->next;
    clone_node = clone_node->next;
    
  }
  return clone_head;
}



int main(int argc, char* argv[]) {

}


这个实现没有考虑链表中有环的情况

 

 

 

 

有趣有爱有价值:http://www.qihu100.com

 

你可能感兴趣的:(复制,复杂链表)