复杂链表的复制及测试

#include<iostream>
using namespace std;
typedef struct ComplexNode
{
 int _data;
 struct ComplexNode*  _next;
 struct ComplexNode* _random;
}ComplexNode;
ComplexNode* BuyNode(int data)
{
 ComplexNode* node = (ComplexNode*)malloc(sizeof(ComplexNode));
 node->_data = data;
 node->_next = NULL;
 node->_random = NULL;
 return node;
}
ComplexNode* CopyList(ComplexNode* head)
{
    //插入拷贝节点
 ComplexNode* cur = head;
 while (cur)
 {
  ComplexNode* next = cur->_next;
  ComplexNode* copy = BuyNode(cur->_data);
  cur->_next = copy;
  copy->_next = next;
  cur = next;
 }
 // 置random
 cur = head;
 while (cur)
 {
  ComplexNode* copy = cur->_next;
  if (cur->_random)
  copy->_random = cur->_random->_next;
  cur = copy->_next;
 }
 // 拆解
 ComplexNode* copyHead = NULL;
 ComplexNode* copyTail = NULL;
 cur = head;
 while (cur)
 {
  ComplexNode* copy = cur->_next;
  ComplexNode* next = copy->_next;
  if (copyHead == NULL)
  {
   copyHead = copyTail = copy;
  }
  else
  {
   copyTail->_next = copy;
   copyTail = copy;
  }
  cur = next;
 }
 return copyHead;
}
void PrintComplexList(ComplexNode* list)
{
 ComplexNode* cur = list;
 while (cur)
 {
  cout << cur->_data << "->";
  cur = cur->_next;
 }
 cout << "NULL" << endl;
 cur = list;
 while (cur)
 {
  if (cur->_random)
   cout << cur->_random->_data << "  ";
  else
   cout << "NULL" << endl;
  cur = cur->_next;
 }
 cout << endl;
}
int main()
{
 ComplexNode* n1 = BuyNode(1);
 ComplexNode* n2 = BuyNode(2);
 ComplexNode* n3 = BuyNode(3);
 ComplexNode* n4 = BuyNode(4);
 n1->_next = n2;
 n2->_next = n3;
 n3->_next = n4;
 n4->_next = NULL;
 n1->_random = n4;
 n2->_random = n2;
 n3->_random = n1;
 n4->_random = NULL;
 PrintComplexList(n1);
 ComplexNode* copy = CopyList(n1);
 PrintComplexList(copy);
 return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值