复杂链表的复制



新的解决方案:



  1. #ifndef COMPLEX_LISTCLONE_H
  2. #define COMPLEX_LISTCLONE_H
  3. #include<iostream>
  4. struct ComplexListNode{
  5. int m_nValue;
  6. struct ComplexListNode *m_pNext;
  7. struct ComplexListNode *m_pSibling;
  8. };
  9. ComplexListNode *complexListCloned(ComplexListNode **head){
  10. cloneNodes(head);
  11. connectpSibingNodes(head);
  12. reconnectNodes(head);
  13. }
  14. void cloneNodes(ComplexListNode **head){
  15. ComplexListNode *pNode=*head;
  16. while(pNode!=NULL){
  17. ComplexListNode *pClonedNode=new ComplexListNode();
  18. pClonedNode->m_nValue=pNode->m_nValue;
  19. pClonedNode->m_pNext=pNode->m_pNext;
  20. pNode->m_pNext=pClonedNode;
  21. pClonedNode->m_pSibling=NULL;
  22. pNode=pNode->m_pNext;
  23. }
  24. }
  25. void connectpSibingNodes(ComplexListNode **head){
  26. ComplexListNode *pNode=*head;
  27. ComplexListNode *pCloned=NULL;
  28. while(pNode!=NULL){
  29. if(pNode->m_pSibling!=NULL){
  30. ComplexListNode *pCloned=pNode->m_pNext;
  31. pCloned->m_pSibling=pNode->m_pSibling->m_pNext;
  32. }
  33. pNode=pCloned->m_pNext;
  34. }
  35. }
  36. ComplexListNode* reconnectNodes(ComplexListNode **head){
  37. if(*head==NULL||head==NULL){
  38. return ;
  39. }
  40. ComplexListNode *pNode=*head;
  41. ComplexListNode *cloneRoot=pNode->m_pNext;
  42. ComplexListNode *cloneNode=cloneRoot;
  43. while(pNode!=NULL){
  44. pNode->m_pNext=cloneNode->m_pNext;
  45. pNode=pNode->m_pNext;
  46. cloneNode->m_pNext=pNode->m_pNext;
  47. cloneNode=cloneNode->m_pNext;
  48. }
  49. return cloneRoot;
  50. }
  51. #endif











posted @ 2015-07-17 19:27  yml435  阅读(146)  评论(0编辑  收藏  举报