现有两个升序链表,且链表中均无重复元素。请设计一个高效的算法,打印两个链表的公共值部分。
给定两个链表的头指针headA和headB,请返回一个vector,元素为两个链表的公共部分。请保证返回数组的升序。两个链表的元素个数均小于等于500。保证一定有公共值
测试样例:
{1,2,3,4,5,6,7},{2,4,6,8,10}
返回:[2.4.6]
代码如下:
package lianbiao;
import java.util.ArrayList;
import java.util.List;
public class lianbiaogonggongzhi {
public static void main(String[] args) {
ListNode headA = new ListNode(3);
ListNode headA2 = new ListNode(4);
ListNode headA3 = new ListNode(5);
headA.next = headA2;
headA2.next = headA3;
ListNode headB = new ListNode(4);
ListNode headB2 = new ListNode(5);
ListNode headB3 = new ListNode(6);
ListNode headB4 = new ListNode(7);
headB.next = headB2;
headB2.next = headB3;
headB3.next = headB4;
int[] arr = lianbiaogonggongzhi.findCommonParts(headA, headB);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
public static int[] findCommonParts(ListNode headA, ListNode headB) {
// write code here
List<Integer> list = new ArrayList<Integer>();
while (headA != null && headB != null) {
if (headA.val < headB.val) {
headA = headA.next;
} else if (headA.val > headB.val) {
headB = headB.next;
} else {
list.add(headA.val);
headA = headA.next;
headB = headB.next;
}
}
int[] arr = new int[list.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
static class ListNode {
int val = 0;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
}