@cxm-2016
2016-12-27T18:02:25.000000Z
字数 758
阅读 1699
算法
版本:2
作者:陈小默
声明:禁止商业,禁止转载
题目:有两个有序链表,我们需要打印出两个链表的公共部分。
比如:
A-> 0,1,2,3,6,7,8
B-> 1,3,4,6,8,9,10
打印 1,3,6,8
思路,谁小谁先走
data class Node(var value: Int, var next: Node?)
fun printCommonPart(head1: Node?, head2: Node?) {
var h1: Node? = head1
var h2: Node? = head2
while (h1 != null && h2 != null) {
if (h1.value < h2.value)
h1 = h1.next
else if (h2.value < h1.value)
h2 = h2.next
else {
println(h1.value)
h1 = h1.next
h2 = h2.next
}
}
}
fun main(args: Array<String>) {
var head1: Node? = null
var head2: Node? = null
var node: Node? = null
intArrayOf(1, 3, 4, 6, 7, 8, 9).forEach { num ->
if (head1 == null) {
head1 = Node(num, null)
node = head1
} else {
node!!.next = Node(num, null)
node = node!!.next
}
}
intArrayOf(2, 4, 5, 6, 7, 8).forEach { num ->
if (head2 == null) {
head2 = Node(num, null)
node = head2
} else {
node!!.next = Node(num, null)
node = node!!.next
}
}
printCommonPart(head1, head2)
}