find and insert after
This commit is contained in:
parent
1a1e7e06b3
commit
fe3c0a3592
@ -10,11 +10,19 @@ class SinglyLinkedList(var headOpt: Option[Node]) {
|
||||
|
||||
|
||||
def findByValue(value: Int): Option[Node] = {
|
||||
None
|
||||
headOpt.flatMap(head => {
|
||||
var node = head
|
||||
while (!node.data.equals(value) && node.next.nonEmpty) {
|
||||
node = node.next.get
|
||||
}
|
||||
|
||||
def findByIndex(index: Int): Option[Node] = {
|
||||
None
|
||||
if (node.data.equals(value)) {
|
||||
return Some(node)
|
||||
} else {
|
||||
//arrive the end of the chain
|
||||
return None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
def insertToHead(value: Int): Unit = {
|
||||
@ -55,9 +63,22 @@ class SinglyLinkedList(var headOpt: Option[Node]) {
|
||||
}
|
||||
}
|
||||
|
||||
def insertAfter(existNode: Node, value: Int) = {}
|
||||
def insertAfter(existNode: Node, value: Int): Unit = {
|
||||
val newNode = new Node(value, None)
|
||||
insertAfter(existNode, newNode)
|
||||
}
|
||||
|
||||
def insertAfter(existNode: Node, newNode: Node) = {}
|
||||
def insertAfter(existNode: Node, newNode: Node): Unit = {
|
||||
existNode.next match {
|
||||
case None =>
|
||||
//exist node is tail
|
||||
newNode.next = None
|
||||
existNode.next = Some(newNode)
|
||||
case Some(next) =>
|
||||
newNode.next = Some(next)
|
||||
existNode.next = Some(newNode)
|
||||
}
|
||||
}
|
||||
|
||||
def insertBefore(existNode: Node, value: Int) = {}
|
||||
|
||||
|
@ -30,4 +30,31 @@ class SinglyLinkedListTest extends FlatSpec with Matchers{
|
||||
|
||||
}
|
||||
|
||||
it should "find by value" in {
|
||||
val list: SinglyLinkedList = new SinglyLinkedList()
|
||||
|
||||
list.insertTail(0)
|
||||
list.insertTail(1)
|
||||
list.insertTail(2)
|
||||
list.insertTail(3)
|
||||
|
||||
list.mkString() should equal("0123")
|
||||
val node1 = list.findByValue(1).get
|
||||
node1.next.get.data should equal(2)
|
||||
}
|
||||
|
||||
it should "insert after node and can find it back" in {
|
||||
val list: SinglyLinkedList = new SinglyLinkedList()
|
||||
|
||||
list.insertTail(0)
|
||||
list.insertTail(1)
|
||||
list.insertTail(3)
|
||||
list.insertTail(4)
|
||||
|
||||
val node1 = list.findByValue(1).get
|
||||
list.insertAfter(node1,2)
|
||||
|
||||
list.mkString() should equal("01234")
|
||||
}
|
||||
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user