[关闭]
@cxm-2016 2016-12-27T10:02:25.000000Z 字数 758 阅读 1578

算法:打印两个有序链表的公共部分

算法

版本:2
作者:陈小默
声明:禁止商业,禁止转载

题目:有两个有序链表,我们需要打印出两个链表的公共部分。
比如:
A-> 0,1,2,3,6,7,8
B-> 1,3,4,6,8,9,10
打印 1,3,6,8
思路,谁小谁先走

  1. data class Node(var value: Int, var next: Node?)
  2. fun printCommonPart(head1: Node?, head2: Node?) {
  3. var h1: Node? = head1
  4. var h2: Node? = head2
  5. while (h1 != null && h2 != null) {
  6. if (h1.value < h2.value)
  7. h1 = h1.next
  8. else if (h2.value < h1.value)
  9. h2 = h2.next
  10. else {
  11. println(h1.value)
  12. h1 = h1.next
  13. h2 = h2.next
  14. }
  15. }
  16. }
  17. fun main(args: Array<String>) {
  18. var head1: Node? = null
  19. var head2: Node? = null
  20. var node: Node? = null
  21. intArrayOf(1, 3, 4, 6, 7, 8, 9).forEach { num ->
  22. if (head1 == null) {
  23. head1 = Node(num, null)
  24. node = head1
  25. } else {
  26. node!!.next = Node(num, null)
  27. node = node!!.next
  28. }
  29. }
  30. intArrayOf(2, 4, 5, 6, 7, 8).forEach { num ->
  31. if (head2 == null) {
  32. head2 = Node(num, null)
  33. node = head2
  34. } else {
  35. node!!.next = Node(num, null)
  36. node = node!!.next
  37. }
  38. }
  39. printCommonPart(head1, head2)
  40. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注