Advertisement
zinch

Copy linked list which has second link to a random node

May 15th, 2015
493
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 1.99 KB | None | 0 0
  1. def source = [[data: '1', rand: 2], [data: '2', rand: 1], [data: '3', rand: 0]]
  2.  
  3. class List {
  4.  
  5.     Node head
  6.  
  7.     class Node {
  8.    
  9.         static int glob_id;
  10.        
  11.         public Node() {
  12.             this.id = glob_id++;
  13.         }
  14.    
  15.         def id
  16.         def next
  17.         def rand
  18.         def data
  19.        
  20.         String toString() {
  21.             "[id=${id}: data=${data}]"
  22.         }
  23.     }
  24. }
  25.  
  26. def create_list(source) {
  27.    
  28.     List list = new List()
  29.    
  30.     List.Node tail
  31.  
  32.     source.each {
  33.         List.Node node = [data: it.data, rand: it.rand] as List.Node
  34.        
  35.         if (! list.head) {
  36.             list.head = node
  37.         }
  38.        
  39.         if (! tail) {
  40.             tail = node
  41.         } else {
  42.             tail.next = node
  43.             tail = node
  44.         }
  45.         it << ['node':node]
  46.     }
  47.    
  48.     source.each {
  49.         it.node.rand = source[it.rand].node
  50.     }
  51.    
  52.     return list    
  53. }
  54.  
  55. List list = create_list(source)
  56.  
  57. def print_list(list) {
  58.  
  59.     List.Node node = list.head
  60.     while (node) {
  61.         println "Node: ${node}, Rand: ${node.rand}"
  62.         node = node.next
  63.     }
  64. }
  65.  
  66. def copy_list(origin) {
  67.  
  68.     List copy = new List()
  69.  
  70.     List.Node copy_tail
  71.  
  72.     //First pass
  73.     List.Node node = origin.head
  74.     while (node) {
  75.    
  76.         List.Node copy_node = [data: node.data, rand: node.rand] as List.Node
  77.        
  78.         next_node = node.next
  79.         node.next = copy_node
  80.        
  81.         if (! copy.head) {
  82.             copy.head = copy_node
  83.         }
  84.        
  85.         if (! copy_tail) {
  86.             copy_tail = copy_node
  87.         } else {
  88.             copy_tail.next = copy_node
  89.             copy_tail = copy_node
  90.         }
  91.         node = next_node
  92.     }
  93.    
  94.     //Second pass
  95.     node = origin.head
  96.     while (node) {
  97.         node.rand = node.rand.next
  98.         node = node.next
  99.     }
  100.     return copy
  101. }
  102.  
  103. println "\nInitial list:"
  104. print_list(list)
  105.  
  106. println "\nCopy list:"
  107. print_list(copy_list(list))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement