dev delete by node

This commit is contained in:
ivan 2018-12-14 20:40:47 +08:00
parent fe3c0a3592
commit 8ea5b66514
2 changed files with 85 additions and 8 deletions

View File

@ -80,16 +80,51 @@ class SinglyLinkedList(var headOpt: Option[Node]) {
}
}
def insertBefore(existNode: Node, value: Int) = {}
def insertBefore(existNode: Node, newNode: Node) = {}
def deleteByNode(node: Node): Option[Node] = {
None
def insertBefore(existNode: Node, value: Int): Unit = {
val newNode = new Node(value, None)
insertBefore(existNode, newNode)
}
def deleteByValue(node: Node): Option[Node] = {
None
def insertBefore(existNode: Node, newNode: Node): Unit = {
headOpt match {
case None =>
throw new IllegalStateException("head node should not be None")
case Some(head) =>
if (existNode.equals(head)) {
insertToHead(newNode)
}
var node = head
while (node.next.nonEmpty && !node.next.get.equals(existNode)) {
node = node.next.get
}
if (node.next.isEmpty) {
throw new IllegalArgumentException("existNode " + existNode + " does not exist in this chain")
}
newNode.next = node.next
node.next = Some(newNode)
}
}
def deleteByNode(node: Node): Unit = {
headOpt.map(head => {
if (head.equals(node)) {
//deleting head
headOpt = node.next
} else {
var p: Node = head
while (p.next.isDefined && !p.next.get.equals(node)) {
p = p.next.get
}
if (p.next.isEmpty) {
throw new IllegalArgumentException("could not find given node")
}
p.next = node.next
}
})
}
def mkString(): String = {

View File

@ -57,4 +57,46 @@ class SinglyLinkedListTest extends FlatSpec with Matchers {
list.mkString() should equal("01234")
}
it should "insert before 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 node3 = list.findByValue(3).get
list.insertBefore(node3,2)
list.mkString() should equal("01234")
}
it should "delete desired node" in {
val list: SinglyLinkedList = new SinglyLinkedList()
list.insertTail(0)
list.insertTail(1)
list.insertTail(2)
list.insertTail(3)
val node1 = list.findByValue(1).get
list.deleteByNode(node1)
list.mkString() should equal("023")
}
it should "delete head node " in {
val list: SinglyLinkedList = new SinglyLinkedList()
list.insertTail(0)
list.insertTail(1)
list.insertTail(2)
list.insertTail(3)
val node0 = list.findByValue(0).get
list.deleteByNode(node0)
list.mkString() should equal("123")
}
}