AddTwo Scala写法
2020-04-12 本文已影响0人
FredricZhu
package addtwo
class ListNode(_x: Int) {
var next: ListNode = null
var x: Int = _x
}
object Solution {
def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
var p = l1
var q = l2
var res = new ListNode(0)
var cur = res
var carry = 0
while ((p != null) || (q != null)) {
val x = if (p != null) p.x else 0
val y = if (q != null) q.x else 0
val sum = x + y + carry
val nodeVal = sum % 10
carry = sum / 10
cur.next = new ListNode(nodeVal)
cur = cur.next
if (p != null) {
p = p.next
}
if (q != null) {
q = q.next
}
}
if (carry > 0) {
cur.next = new ListNode(carry)
}
res.next
}
def main(args: Array[String]): Unit = {
var head = new ListNode(2)
var second = new ListNode(4)
var third = new ListNode(3)
head.next = second
second.next = third
var head1 = new ListNode(5)
var second1 = new ListNode(6)
var third1 = new ListNode(4)
head1.next = second1
second1.next = third1
val res = addTwoNumbers(head, head1)
var resHead = res
while(resHead != null) {
print(resHead.x+" ")
resHead = resHead.next
}
}
}