思路
因为是有序链表,所以从两个链表的头开始进行如下判断
- 如果 head1 的值小于 head2 那么 head1 下移
- 如果 head1 的值大于 head2 那么 head2 下移
- 如果 head1 和 head2 的值相等,则打印这个值,并且 head1 和 head2 都下移
- 如果 head1 和 head2 中有任何一个移动到
null,则整个过程结束 - head1 和 head2 相等值,存入数组变量
result中并返回
实现
/**** 打印两个有序链表中公共部分* @param {*} head1* @param {*} head2*/function printCommonPart(head1, head2) {let result;while (head1 !== null && head2 !== null) {if (head1.value < head2.value) {head1 = head1.next;} else if (head1.value > head2.value) {head2 = head2.next;} else {result.push(head1.value);head1 = head1.next;head2 = head2.next;}}return result;}
