剑指offer: 复杂链表的复制
2017-03-18 18:32
429 查看
题目:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:
1.不考虑随机指针,复制节点并插入其后方位置
2.用两个指针同时遍历,复制随机指针
3.借助一个节点变量,将链表拆成两个
代码:
/*
public class RandomListNode
{
public int label;
public RandomListNode next, random;
public RandomListNode (int x)
{
this.label = x;
}
}*/
class Solution
{
public RandomListNode Clone(RandomListNode pHead)
{
// write code here
if(pHead == null)
return null;
RandomListNode cur = pHead;
while(cur != null)
{
RandomListNode node = new RandomListNode(cur.label);
node.next = cur.next;
cur.next = node;
cur = node.next;
}
cur = pHead;
while(cur != null)
{
RandomListNode next = cur.next;
if(cur.random != null)
{
next.random = cur.random.next;
}
cur = next.next;
}
cur = pHead;
RandomListNode newHead = cur.next;
while(cur.next != null)
{
RandomListNode temp = cur.next;
cur.next = temp.next;
cur = temp;
}
return newHead;
}
}
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:
1.不考虑随机指针,复制节点并插入其后方位置
2.用两个指针同时遍历,复制随机指针
3.借助一个节点变量,将链表拆成两个
代码:
/*
public class RandomListNode
{
public int label;
public RandomListNode next, random;
public RandomListNode (int x)
{
this.label = x;
}
}*/
class Solution
{
public RandomListNode Clone(RandomListNode pHead)
{
// write code here
if(pHead == null)
return null;
RandomListNode cur = pHead;
while(cur != null)
{
RandomListNode node = new RandomListNode(cur.label);
node.next = cur.next;
cur.next = node;
cur = node.next;
}
cur = pHead;
while(cur != null)
{
RandomListNode next = cur.next;
if(cur.random != null)
{
next.random = cur.random.next;
}
cur = next.next;
}
cur = pHead;
RandomListNode newHead = cur.next;
while(cur.next != null)
{
RandomListNode temp = cur.next;
cur.next = temp.next;
cur = temp;
}
return newHead;
}
}
相关文章推荐
- 剑指Offer 26 复杂链表的复制
- 【剑指Offer面试编程题】题目1524:复杂链表的复制--九度OJ
- 剑指Offer面试题:24.复杂链表的复制
- 剑指offer 复杂链表的复制
- 剑指offer-面试题26-复杂链表的复制
- 剑指offer面试题26-复杂链表的复制
- 剑指offer——35复杂链表的复制
- 剑指offer--复杂链表的复制
- 剑指offer-复杂链表的复制
- 剑指offer—复杂链表的复制
- 剑指offer-第四章解决面试题思路(复杂链表的复制)
- 剑指offer面试题26-复杂链表的复制
- 剑指offer之二十一---复杂链表的复制
- 剑指offer-25.复杂链表的复制
- 【剑指Offer】复杂链表的复制
- 剑指offer:复杂链表的复制
- 剑指offer-复杂链表的复制
- [剑指offer]复杂链表的复制
- 剑指offer——复杂链表的复制_
- 【剑指offer】第三十四题(二叉树中和尾某一值的路径) 和 第三十五题(复杂链表的复制)