题目描述
输入两个链表,找出它们的第一个公共结点。
首先,想到的解题思路是:让第一个链表的每一个数和第二个链表的每一个数作比较,找出第一个相等的节点。
完整代码:
public class FindFirstCommonNode {
public static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
ListNode head2 = new ListNode(2);
head2.next = new ListNode(3);
head2.next.next = new ListNode(5);
head2.next.next.next = new ListNode(4);
FindFirstCommonNode(head, head2);
}
public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
//遍历pHead1, 让他的每一个数都和pHead2比较一次
while (pHead1 != null) {
//pHead1当前值
int pv1 = pHead1.val;
//把pHead2赋给一个临时链表, 让pv1去和临时链表比较
ListNode p2 = new ListNode(0);
p2 = pHead2;
while (p2 != null) {
int pv2 = p2.val;
if (pv1 == pv2) {
System.out.println(pHead1.val);
return pHead1;
}
p2 = p2.next;
}
pHead1 = pHead1.next;
}
return null;
}
}