定义节点
class ListNode {
var next: ListNode = _
var x: Int = _
def this(x: Int) = {
this
this.x = x
}
override def toString: String = s"x=>$x"
}
定义方法
class LinkedList {
var head = new ListNode(0)
def getHead(): ListNode = this.head
def add(listNode: ListNode): Unit = {
var temp = this.head
while (temp.next != null) {
temp = temp.next
}
temp.next = listNode
}
def list(listNode: ListNode): Unit = {
var temp = head.next
while (temp.next != null) {
println(s"$temp")
temp = temp.next
}
}
def compair(head1: ListNode, head2: ListNode): ListNode = {
var node1 = head1.next
var node2 = head2.next
//定义输出节点
val head = new ListNode()
var current = new ListNode()
head.next = current //将head的next指向current
while (node1 != null && node2 != null) {
if (node1.x < node2.x) {
current.x = node1.x
current.next = new ListNode()
current = current.next
node1 = node1.next
} else {
current.x = node2.x
current.next = new ListNode()
current = current.next
node2 = node2.next
}
}
while (node1 != null) {
current.x = node1.x
current.next = new ListNode()
current = current.next
node1 = node1.next
}
while (node2 != null) {
current.x = node2.x
current.next = new ListNode()
current = current.next
node2 = node2.next
}
head
}
}
主函数
package Algotithm
object LinkedListDemo {
def main(args: Array[String]): Unit = {
val list1 = new LinkedList
for (i <- 1 to 5 by 2) {
val node = new ListNode(i)
list1.add(node)
}
println(s"list1=========")
list1.list(list1.getHead())
val list2 = new LinkedList
for (i <- 1 to 10 by 3) {
val node = new ListNode(i)
list2.add(node)
}
println(s"list2=========")
list2.list(list2.getHead())
println(s"=====================")
val list3 = new LinkedList
val node = list3.compair(list1.getHead(), list2.getHead())
list3.head = node // 将 node 赋值给 list3 的头节点
list3.list(node)
}
}
结果
总结
1、定义方法时,需要重新new节点,将值付给该节点
2、调用方法得到节点之后,需要将该节点赋值给 list 的头节点