Kotlinlearncs.online LogoJava
Return to List

Test Writing: SimpleLinkedList add

Created By: Geoffrey Challen
/ Version: 2020.10.0

Starting with the SimpleLinkedList class below, complete the code for add. You'll want review the rest of the code to understand how this list implementation works and how to walk a linked list and manipulate the references properly.

add takes the position to add at as an Int as its first parameter and the Any reference to add as its second. add should add the element to the list, increasing the size by one and shifting elements after the add position backward. You should require that the passed position is valid for this list. But note that you should allow adding a new item to the end of the existing list.

When you are done, here is how your SimpleLinkedList class should work:

Test Design Challenge

You're challenge is to write tests for this problem described above.

  • Provide a public class named TestSimpleLinkedList with a single non-private class method named test that accepts no arguments and does not return a value.
  • If the implementation of the class described above is incorrect, your test method should throw an exception.
  • If it is correct, do not throw an exception.
  • You may want to use Kotlin's assert or check methods
class SimpleLinkedList(values: Array<Any?>) {
private inner class Item(var value: Any?, var next: Item?)
private var start: Item? = null
private var size = 0
init {
for (value in values.reversed()) {
add(0, value)
}
}
fun size() = size
private fun walkTo(index: Int): Item {
require(index in 0 until size)
var current = start
repeat(index) {
current = current!!.next
}
return current!!
}
fun add(
index: Int,
value: Any?,
) {
TODO("Not implemented")
}
fun get(index: Int): Any? {
return walkTo(index).value
}
fun set(
index: Int,
newValue: Any?,
) {
walkTo(index).value = newValue
}
}