Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit03318a7

Browse files
authored
Merge pull requestneetcode-gh#1055 from Mahim1997/dev/138_swift
138. Copy List with Random Pointer
2 parents57d9ba0 +065d74e commit03318a7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Definition for a Node.
3+
* public class Node {
4+
* public var val: Int
5+
* public var next: Node?
6+
* public var random: Node?
7+
* public init(_ val: Int) {
8+
* self.val = val
9+
* self.next = nil
10+
* self.random = nil
11+
* }
12+
* }
13+
*/
14+
15+
classSolution{
16+
// Cache of mapping from old to new nodes
17+
privatevarmapping:[Node?:Node?]=[:]
18+
19+
func copyRandomList(_ head:Node?)->Node?{
20+
// Base case: Nil node
21+
guardlet node= headelse{returnnil}
22+
23+
// Mapping exists
24+
guardmapping[node]==nilelse{returnmapping[node]!}
25+
26+
// Create new node
27+
letnewNode=Node(node.val)
28+
29+
// Add to cache (i.e. 'visit' this node)
30+
mapping[node]= newNode
31+
32+
// Recursive calls (preorder -> children calls)
33+
newNode.next=copyRandomList(node.next)
34+
newNode.random=copyRandomList(node.random)
35+
36+
return newNode
37+
}
38+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp