//头文件 #pragma once typedef int DataType; typedef struct ComplexNode { DataType _data; // 数据 struct ComplexNode* _next; // 指向下一个节点的指针 struct ComplexNode* _random; // 指向随机节点 }ComplexNode,*pComplexNode; void BuyNode(pComplexNode& pNode,DataType x); void PushBack(pComplexNode& pHead,DataType x); void CopyCplexList(pComplexNode pHead,pComplexNode& NewpHead); pComplexNode Find(pComplexNode pHead, DataType Data); void PrintLinkList(pComplexNode pHead); //函数文件 #include<stdio.h> #include"ComplexList.h" #include<assert.h> #include<malloc.h> //创建节点 void BuyNode(pComplexNode& pNode, DataType x) { pNode = (pComplexNode)malloc(sizeof(ComplexNode)); pNode->_data = x; pNode->_next = NULL; pNode->_random = NULL; } //头插 void PushBack(pComplexNode& pHead,DataType x) { pComplexNode tmp = pHead; if (pHead == NULL) { BuyNode(pHead, x); return; } while (tmp->_next != NULL) { tmp = tmp->_next; } BuyNode(tmp->_next, x); } //复杂链表复制 void CopyCplexList(pComplexNode pHead, pComplexNode& NewpHead) { pComplexNode tmp = pHead; pComplexNode head = pHead; if (pHead == NULL) return; while (head != NULL) { tmp = head->_next; BuyNode(NewpHead, head->_data); head->_next = NewpHead; NewpHead->_next = tmp; head = tmp; } head = pHead; while (head != NULL) { tmp = head->_next; if (head->_random == NULL) tmp->_random == NULL; else tmp->_random = head->_random->_next; head = head->_next->_next; } head = pHead; NewpHead = head->_next; while (head!=NULL) { tmp = head->_next; head->_next = tmp->_next; head = tmp->_next; if (head == NULL) return; tmp->_next = head->_next; } } //查找 pComplexNode Find(pComplexNode pHead, DataType Data) { pComplexNode tmp = pHead; assert(pHead); while (tmp) { if (tmp->_data == Data) return tmp; tmp = tmp->_next; } return NULL; } //输出 void PrintLinkList(pComplexNode pHead) { pComplexNode tmp = pHead; if (pHead == NULL) { printf("链表为空!\n"); } while (tmp) { printf("%d ", tmp->_data); tmp = tmp->_next; } printf("\n"); } //测试用例 主函数 #include<stdio.h> #include"ComplexList.h" void test1() { pComplexNode pHead=NULL,NewpHead=NULL; PushBack(pHead, 1); PushBack(pHead, 2); PushBack(pHead, 3); PushBack(pHead, 4); PrintLinkList( pHead); Find(pHead, 1)->_random = Find(pHead, 3); Find(pHead, 2)->_random = Find(pHead, 4); Find(pHead, 3)->_random = Find(pHead, 2); Find(pHead, 4)->_random = Find(pHead, 1); CopyCplexList(pHead, NewpHead); PrintLinkList(NewpHead); } int main() { test1(); return 0; }
原文地址:http://shaungqiran.blog.51cto.com/10532904/1707788