#138 Copy List with Random Pointer
A linked list of length
n
is given such that each node contains an additional random pointer, which could point to any node in the list, ornull
.Construct a deep copy of the list. The deep copy should consist of exactly
n
brand new nodes, where each new node has its value set to the value of its corresponding original node. Both thenext
andrandom
pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.For example, if there are two nodes
X
andY
in the original list, whereX.random --> Y
, then for the corresponding two nodesx
andy
in the copied list,x.random --> y
.Return the head of the copied linked list.
The linked list is represented in the input/output as a list of
n
nodes. Each node is represented as a pair of[val, random_index]
where:
val
: an integer representingNode.val
random_index
: the index of the node (range from0
ton-1
) that therandom
pointer points to, ornull
if it does not point to any node.Your code will only be given the
head
of the original linked list.
Example 1:
解题思路:
Deep Copy是为了避免改副本时,原来的数据也被改变。所以就创建了另外一个地址的副本。相反的是shallow copy。副本和原本都是指向同一个对象。副本改了原本也被改变。
Python有直接的funciton可以用。
import copy之后,copy.deepcopy(head)就行。
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
import copy
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
# deep copy do not share the same reference as the original one
deepcopy = copy.deepcopy(head)
return deepcopy
runtime:
参考一下19ms的:
新创建一个dict,存原本和副本有个对应的关系。 先把点存完,然后再把next 和random指针依照原本,指向副本里的点。
#61 Rotate List
Given the
head
of a linked list, rotate the list to the right byk
places.
Example 1:
Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
解题思路:
用三个pointer:h, tail, sever 分别标注头尾和切割点。head = sever.next, sever.next = None, tail.next = h.来完成rotate。
一开始三个指针都指向head,然后while循环往后送。切割点是算出来链的长度后,用这个长度减去k除以长度后得到的余数再减一得到的。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or k == 0: return head
length, sever, h, tail = 1, head, head, head
# send tail pointer to the end node
while tail.next:
tail = tail.next
length += 1
if length == 1 or k%length == 0: return head
k = length - k % length - 1
# get to the sever point
while k:
sever = sever.next
k -= 1
head = sever.next
sever.next = None
tail.next = h
return head
runtime:
参考forum看到,length == 1可以用not head.next来替换。其他部分的思路都相似。链表专题16题做完了。接下来二叉树专题