复杂链表的复制
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;
}
这里的思路是将要复制的新节点都插入复制的那个结点的后面,那么新节点的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;
}
相关文章推荐
- CATransform3D的使用以及各个参数的含义
- LYSE-高阶函数
- 自己的第一个单片机程序
- Ubuntu 安装 cscope 和 ctags
- Cmd命令行编译c#文件
- 搞不定linux下的无线网卡驱动的权宜之计
- net-snmp源码VS2013编译添加加密支持(OpenSSL)
- 第13周—项目4 Floyd算法验证
- 冒泡排序函数,可以给任意类型的数据排序,比如整形数组,字符数组,字符串数组等
- iOS开发49-iOS Mac OS X Openfire的安装与卸载
- NavigationController
- javascript的navigator对象
- 异步流程控制库GoWithTheFlow
- 源码解析EventBus
- 1008. Elevator (20)
- [BZOJ1787][Ahoi2008]Meet 紧急集合&&[BZOJ1832][AHOI2008]聚会
- iOS修改tabbar的背景颜色
- 1008. Elevator (20)
- 获得每日,每周,每月的0点和24点的时间戳
- 小刚之问引发的思索