思路:这题就是双指针,然后如果指针A和指针B所指向的数据是一样的,就一起往后跳,如果不相同,比如A指向的数据大,就把A指针向后移动,如果B指向的数据大,就把B向后移,while 的条件是A和B都没到达链表的结尾。
代码如下:
static class ListNode {
int data;
ListNode next;
ListNode(int val) {
this.data = val;
}
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
int n = cin.nextInt();
ListNode list1 = new ListNode(0);
ListNode cur = list1;
for (int i = 0; i < n; i++) {
int a = cin.nextInt();
cur.next = new ListNode(a);
cur = cur.next;
}
int m = cin.nextInt();
ListNode list2 = new ListNode(0);
cur = list2;
for (int i = 0; i < m; i++) {
int b = cin.nextInt();
cur.next = new ListNode(b);
cur = cur.next;
}
ListNode res = find(list1.next,list2.next);//把公共的部分打印出来
while (res != null){
int ans = res.data;
System.out.print(ans+" ");
res = res.next;
}
System.out.println();
}
}
public static ListNode find(ListNode point1, ListNode point2) {
if (point1 == null || point2 == null) return null;
ListNode head = new ListNode(-1);
ListNode pre = head;
while (point1 != null && point2 != null) {
if (point1.data == point2.data) {
ListNode newNode = new ListNode(point1.data);
point1 = point1.next;
point2 = point2.next;
pre.next = newNode;
pre = pre.next;
}else if(point1.data > point2.data){
point1 = point1.next;
}else {
point2 = point2.next;
}
}
return head.next;
}
改进,,其看了别人的方法,发现其实这题根本用不到链表,数组也是一样可以完成的,如下:
package tengxun;
import java.util.Scanner;
/**
* Created by IntelliJ IDEA.
*
* @Author:
* @Email:
* @Date: 2020/9/6
* @Time: 20:03
* @Version: 1.0
* @Description: Description
*/
public class First {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr1 = new int[n];
for (int i = 0; i < n; i++) {
arr1[i] = sc.nextInt();
}
int m = sc.nextInt();
int[] arr2 = new int[m];
for (int i = 0; i < m; i++) {
arr2[i] = sc.nextInt();
}
sc.close();
int p1 = 0, p2 = 0;
while (p1 < n && p2 < m) {
if (arr1[p1] == arr2[p2]) {
System.out.print(arr1[p1] + " ");
p1++;
p2++;
} else if (arr1[p1] < arr2[p2]) {
p2++;
} else {
p1++;
}
}
}
}