Last active
December 17, 2018 05:51
-
-
Save hkurokawa/2f3d5937869e2954471f4bb3672c50c4 to your computer and use it in GitHub Desktop.
Sample LinkedList implementation supporting flatten()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.IllegalStateException | |
class MyLinkedList : Iterable<Any> { | |
var head: Node = Node(Any()) | |
fun add(value: Any) { | |
var n: Node = head | |
while (n.next != null) { | |
n = n.next!! | |
} | |
n.next = Node(value) | |
} | |
fun flatten() { | |
fun insert(node: Node, value: Any): Node { | |
val nn = node.next | |
val newNode = Node(value) | |
newNode.next = nn | |
node.next = newNode | |
return newNode | |
} | |
var n: Node = head | |
while (n.next != null) { | |
val nn = n.next!! | |
if (nn.value is MyLinkedList) { | |
n.next = nn.next // remove the sublist to flatten from the list | |
nn.value.forEach { n = insert(n, it) } | |
} | |
n = nn | |
} | |
} | |
override fun iterator(): Iterator<Any> { | |
return object : Iterator<Any> { | |
private var ptr: Node = head | |
override fun hasNext() = ptr.next != null | |
override fun next(): Any { | |
if (ptr.next == null) throw IllegalStateException( | |
"hasNext() should be called to verify the next value exists before next()") | |
val ret = ptr.next!!.value | |
ptr = ptr.next!! | |
return ret | |
} | |
} | |
} | |
override fun toString(): String { | |
val sb = StringBuilder("[") | |
this.forEach { sb.append(it).append(", ") } | |
if (sb.length > 1) { | |
sb.setLength(sb.length - 2) | |
} | |
sb.append("]") | |
return sb.toString() | |
} | |
} | |
class Node(val value: Any) { | |
var next: Node? = null | |
} | |
fun main(args: Array<String>) { | |
val list1 = MyLinkedList() | |
list1.add(1) | |
list1.add(2) | |
val list2 = MyLinkedList() | |
list2.add(3) | |
list2.add(list1) | |
list2.add(4) | |
list2.flatten() | |
println(list2) // [3, 1, 2, 4] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment