Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def source = [[data: '1', rand: 2], [data: '2', rand: 1], [data: '3', rand: 0]]
- class List {
- Node head
- class Node {
- static int glob_id;
- public Node() {
- this.id = glob_id++;
- }
- def id
- def next
- def rand
- def data
- String toString() {
- "[id=${id}: data=${data}]"
- }
- }
- }
- def create_list(source) {
- List list = new List()
- List.Node tail
- source.each {
- List.Node node = [data: it.data, rand: it.rand] as List.Node
- if (! list.head) {
- list.head = node
- }
- if (! tail) {
- tail = node
- } else {
- tail.next = node
- tail = node
- }
- it << ['node':node]
- }
- source.each {
- it.node.rand = source[it.rand].node
- }
- return list
- }
- List list = create_list(source)
- def print_list(list) {
- List.Node node = list.head
- while (node) {
- println "Node: ${node}, Rand: ${node.rand}"
- node = node.next
- }
- }
- def copy_list(origin) {
- List copy = new List()
- List.Node copy_tail
- //First pass
- List.Node node = origin.head
- while (node) {
- List.Node copy_node = [data: node.data, rand: node.rand] as List.Node
- next_node = node.next
- node.next = copy_node
- if (! copy.head) {
- copy.head = copy_node
- }
- if (! copy_tail) {
- copy_tail = copy_node
- } else {
- copy_tail.next = copy_node
- copy_tail = copy_node
- }
- node = next_node
- }
- //Second pass
- node = origin.head
- while (node) {
- node.rand = node.rand.next
- node = node.next
- }
- return copy
- }
- println "\nInitial list:"
- print_list(list)
- println "\nCopy list:"
- print_list(copy_list(list))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement