zoukankan      html  css  js  c++  java
  • 复杂链表的复制

    实现一个函数复制一个复杂链表。在复杂链表中,每个结点除了有一个m_pNext指针指向下一个结点外,还有一个m_pSibling指向链表中的任意结点或者NULL。

    1 //结点定义
    2 struct ComplexListNode 
    3 {
    4     int              m_nValue;
    5     ComplexListNode* m_pNext;
    6     ComplexListNode* m_pSibling;
    7 };
     1 //复制原始链表的任意结点N,并创建新的结点N~,再把N~链接到N的后面
     2 void CloneNodes( ComplexListNode* pHead)
     3 {
     4     if (pHead == NULL)
     5     {
     6         return;
     7     }
     8     ComplexListNode* pNode = pHead;
     9     while (pNode)
    10     {
    11         ComplexListNode* pClone = new ComplexListNode();
    12         pClone->m_nValue = pNode->m_nValue ;
    13         pClone->m_pNext = pNode->m_pNext ;
    14         pNode->m_pNext = pClone;
    15         pClone->m_pSibling = NULL;
    16         pNode = pClone->m_pNext;
    17 
    18     }
    19 }
    20 //如果原始链表的结点N的m_pSibling指向S,则它对应的复制结点N~的m_pSibling指向S的下一个结点S~
    21 void ConnectSiblingNodes(ComplexListNode* pHead)
    22 {
    23     if (pHead == NULL)
    24     {
    25         return;
    26     }
    27     
    28     while (pHead)
    29     {
    30         ComplexListNode* pClone = pHead->m_pNext;
    31         if (pHead->m_pSibling)
    32         {
    33             pClone->m_pSibling = pHead->m_pSibling->m_pNext;
    34         }
    35         pHead = pClone->m_pNext ;
    36     }
    37 }
    38 //把第二步得到的链表拆分成两个链表,奇数位置上的结点组成原始链表,偶数位置上的结点组成复制出来的链表
    39 ComplexListNode* ReconnectNodes(ComplexListNode* pHead)
    40 {
    41     if (pHead == NULL)
    42     {
    43         return NULL;
    44     }
    45     ComplexListNode* pNode = pHead ;
    46     ComplexListNode* pCloneHead = pHead->m_pNext;
    47     ComplexListNode* pCloneNode = pHead->m_pNext;
    48     while (pCloneNode->m_pNext)
    49     {
    50         pNode->m_pNext = pCloneNode->m_pNext ;
    51         pNode = pNode->m_pNext ;
    52         pCloneNode->m_pNext = pNode->m_pNext ;
    53         pCloneNode = pCloneNode->m_pNext ;
    54     }
    55     pNode->m_pNext = NULL ;
    56 
    57     return pCloneHead ;
    58 }
    59 
    60 ComplexListNode* Clone(ComplexListNode* pHead)
    61 {
    62     if (pHead == NULL)
    63     {
    64         return NULL;
    65     }
    66     CloneNodes(pHead);
    67     ConnectSiblingNodes(pHead);
    68     return ReconnectNodes(pHead);
    69 }
  • 相关阅读:
    HDU1080(DP)
    hdu1059(多重背包优化)
    Codeforces Round #190 (Div. 2).D
    jQuery的安装
    JDBC-Statement,prepareStatement,CallableStatement的比较
    execute、executeQuery和executeUpdate之间的区别
    Word操作总结
    Excel 操作总结
    notepad 操作总结
    3.CSS使用基础(2)
  • 原文地址:https://www.cnblogs.com/csxcode/p/3712531.html
Copyright © 2011-2022 走看看