Advertisement
HXXXXJ

Copy List with Random node

Mar 27th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.54 KB | None | 0 0
  1.  
  2.  
  3. class Node : Hashable{
  4.     var next : Node?
  5.     var random : Node?
  6.     var key : String
  7.     init(_ str: String) {
  8.         self.key = str
  9.     }
  10.     static func == (ls: Node, rs: Node) -> Bool{
  11.         return ls.key == rs.key
  12.     }
  13.     func hash(into hasher: inout Hasher) {
  14.        
  15.     }
  16. }
  17.  
  18.  
  19. var map = [Node: Node]() //orignal - copied
  20.  
  21. func copyListWithRandom(_ node: Node?) -> Node?{
  22.     guard let node = node else {
  23.         return nil
  24.     }
  25.     let copyHeader = Node(node.key)
  26.     map[node] = copyHeader
  27.    
  28.     var runner : Node? = node
  29.    
  30.     while runner != nil{
  31.         let curr = runner!
  32.         let new = getNewNode(curr)!
  33.         new.next =  getNewNode(curr.next)
  34.         new.random = getNewNode(curr.random)
  35.         runner = curr.next
  36.     }
  37.     return getNewNode(node)
  38. }
  39.  
  40. func getNewNode(_ old : Node?) -> Node?{
  41.     guard let old = old else { return nil }
  42.     if let node = map[old]{
  43.         return node
  44.     }
  45.     let node = Node(old.key)
  46.     map[old] = node
  47.     return node
  48. }
  49.  
  50.  
  51.  
  52.  
  53. let n1 = Node("a")
  54.  
  55. let n2 = Node("b")
  56. let n3 = Node("c")
  57. let n4 = Node("d")
  58.  
  59. n1.next = n2
  60. n2.next = n3
  61. n3.next = n4
  62. n4.random = n1
  63. n1.random = n3
  64.  
  65.  
  66. func printNode(_ node: Node?){
  67.     var n = node
  68.     while n != nil {
  69.         print(n!.key)
  70.         if let random = n!.random{
  71.             print("  random: \(random.key)")
  72.         }
  73.         n = n!.next
  74.     }
  75. }
  76.  
  77. print("BEFORE ---------")
  78. printNode(n1)
  79.  
  80. let copy = copyListWithRandom(n1)
  81. print("")
  82. print("")
  83. print("COPY ---------")
  84. printNode(copy)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement