剑指offer--day12

1.1 题目:复杂链表的复制:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

1.2 思路:

我们这里采用三步:

  • 第一步:复制复杂指针的label和next。但是这次我们把复制的结点跟在元结点后面,而不是直接创建新的链表;
  • 第二步:设置复制出来的结点的random。因为新旧结点是前后对应关系,所以也是一步就能找到random;
  • 第三步:拆分链表。奇数是原链表,偶数是复制的链表。

1.3 代码:

 1 # -*- coding:utf-8 -*-
 2 # class RandomListNode:
 3 #     def __init__(self, x):
 4 #         self.label = x
 5 #         self.next = None
 6 #         self.random = None
 7 class Solution:
 8     # 返回 RandomListNode
 9     def Clone(self, pHead):
10         # write code here
11         if pHead == None:
12             return None
13         # 复制节点,并将节点放置在原节点之后
14         pCur = pHead
15         while(pCur != None):
16             # 复制节点
17             node = RandomListNode(pCur.label)
18             # 下面两行代码是将复制出来的节点插入到原节点之间
19             node.next = pCur.next
20             pCur.next = node
21             # 插入成功之后,将pCur指向下一个节点
22             pCur = node.next
23         # 复制random节点
24         pCur = pHead
25         while (pCur != None):
26             if pCur.random != None:
27                 # 将复制节点的random指针原节点的random指针所指向的节点的后一个
28                 pCur.next.random = pCur.random.next
29             # 将pCur指向下一个原节点,pCur.next为复制节点
30             pCur = pCur.next.next
31         head = pHead.next  # 找到复制链表的头节点了
32         cur = pHead.next
33         # 将新旧链表分离
34         pCur = pHead
35         while (pCur != None):
36             pCur.next = pCur.next.next
37             if cur.next != None:
38                 cur.next = cur.next.next
39             cur = cur.next
40             pCur = pCur.next
41         return head

猜你喜欢

转载自www.cnblogs.com/WJZheng/p/11273234.html