复制一个链表

来源:互联网 发布:阿里云个人网站 编辑:程序博客网 时间:2024/05/16 11:52
typedef struct LNode{ int data; LNode *next; //指向下一个 LNode *Random; //随意指向一个节点}Lnode,*LinkList;


 

////////////////////////////////////////////////////////////////////////////复制链表,链表不带环的情况下LNode *Copy_Lnode(LNode *src_head,LNode *dest_head ) //src_head 为原来的链表 {LNode *p_src;p_src=src_head;LNode *p_dest;while(p_src)  //插入与链表个数相同的节点,并且插入每个节点之后{p_dest=(LNode*)malloc(sizeof(LNode));p_dest->data=p_src->data;p_dest->next=p_src->next;p_dest->Random=p_src->Random;p_src->next=p_dest;p_src=p_dest->next;}p_src=src_head;while(p_src){p_src->next->Random=p_src->Random->next; //复制随意的指针p_src=p_src->next->next;                 //移动指针}//把两个链表分开dest_head=src_head->next;//p_dest=dest_head;p_src=src_head;while (1){p_src->next=p_dest->next;p_src=p_src->next;p_dest->next=p_src->next;p_dest=p_src->next;if (p_dest->next==NULL){p_src->next=NULL;break;}}return dest_head;}

原创粉丝点击