思路

因为是有序链表,所以从两个链表的头开始进行如下判断

  • 如果 head1 的值小于 head2 那么 head1 下移
  • 如果 head1 的值大于 head2 那么 head2 下移
  • 如果 head1 和 head2 的值相等,则打印这个值,并且 head1 和 head2 都下移
  • 如果 head1 和 head2 中有任何一个移动到 null,则整个过程结束
  • head1 和 head2 相等值,存入数组变量result中并返回

实现

  1. /**
  2. *
  3. * 打印两个有序链表中公共部分
  4. * @param {*} head1
  5. * @param {*} head2
  6. */
  7. function printCommonPart(head1, head2) {
  8. let result;
  9. while (head1 !== null && head2 !== null) {
  10. if (head1.value < head2.value) {
  11. head1 = head1.next;
  12. } else if (head1.value > head2.value) {
  13. head2 = head2.next;
  14. } else {
  15. result.push(head1.value);
  16. head1 = head1.next;
  17. head2 = head2.next;
  18. }
  19. }
  20. return result;
  21. }