您的位置:首页 > 其它

复杂链表的复制

2015-11-27 20:38 323 查看
一个复杂链表中有两个指针,一个指针指向下一个结点,另一个指针指向链表中任意一个结点,要实现next的指向很简单,关键问题是指向任意位置的指向如何实现,

这里的思路是将要复制的新节点都插入复制的那个结点的后面,那么新节点的rand就是原结点的rand的next。具体代码如下:

List* Create_node(DataType x) //开辟一个新的结点

{

List* tmp;

tmp = (List *)malloc(sizeof(DataType));

tmp->data = x;

tmp->next = NULL;

tmp->rand = NULL;

return tmp;

}

List *Copy_List(List *head)

{

List *newhead = NULL;

List *newnode = NULL;

List *cur = head;

List *newhead_tail = NULL;

while(cur != NULL){

newnode = Create_node(cur->data);

newnode->next = cur->next;

cur->next = newnode;

cur = cur->next->next;

}

cur = head;

while(cur != NULL){

cur->next->rand = cur->rand->next;

cur = cur->next->next;

}

cur = head;

newhead = cur->next;

cur->next = cur->next->next;

newhead_tail = head;

cur = cur->next;

while(cur != NULL){

newhead_tail->next = cur->next;

cur->next = cur->next->next;

cur = cur->next;

}

return newhead;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: