进步感受:
well done ~~!自己做出来了,这道题思路很简单,思路如下:
1、先求出各自链表长度,l1, l2;
2、再用n = Math.abs(l1 - l2),让长的链表先走n步
3、之后,就可以在共同其他,找到公共节点了
解题思路:
这里说下官方的解题思路,是用循环的思路,
如果让大家,p1和p2指针,都走同样的x+y+z的路程,那就相当于走了一个圆,大家一定会相遇了,就是这样的思路。
巧妙的地方,在于链表指针的切换,当某个链表遍历到尾节点时,切换到另一个链表再进行遍历。
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { /** * 官方的做法 */ public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if(pHead1 == null || pHead2 == null) { return null; } ListNode p1 = pHead1; ListNode p2 = pHead2; while(p1!=p2) { p1 = (p1 == null? pHead2 : p1.next); p2 = (p2 == null? pHead1 : p2.next); } return p1; } // 我的思路很简单,先统计他们的各自链表的长度,之后,用长度相减得出同步开始走的地方 // 不断的一一比对就可以找到相同的节点了 // 如果没有相同节点,也会因为走到尾节点尾null而返回正常的空值 public ListNode FindFirstCommonNode2(ListNode pHead1, ListNode pHead2) { if(pHead1 == null || pHead2 == null) { return null; } int length1 = getListsNodeLength(pHead1); int length2 = getListsNodeLength(pHead2); ListNode cur1 = pHead1; ListNode cur2 = pHead2; if (length1 >= length2) { int n = length1 - length2; cur1 = pHead1; while (n > 0) { cur1 = cur1.next; n--; } cur2 = pHead2; return findTheSameNodeWithSameLength(cur1, cur2); } else { int n = length2 - length1; cur2 = pHead2; while (n > 0) { cur2 = cur2.next; n--; } cur1 = pHead1; return findTheSameNodeWithSameLength(cur1, cur2); } } int getListsNodeLength(ListNode node) { int length = 0; ListNode curr = node; while (curr != null) { length++; curr = curr.next; } return length; } ListNode findTheSameNodeWithSameLength(ListNode p1, ListNode p2) { while (p1 != p2) { p1 = p1.next; p2 = p2.next; } return p1; } }