[leetCode]剑指 Offer 52. 两个链表的第一个公共节点
解法一
第一次遍历得到链表长度,找到较长的链表
第二次遍历现在较长的链表上走几步,两个链表再同时遍历以同时达到尾节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// 得到两个链表的长度
int lenA = getListLength(headA);
int lenB = getListLength(headB);
int lenDif = lenA - lenB;
ListNode headLong = headA;
ListNode headShort = headB;
if(lenDif < 0) {
headLong = headB;
headShort = headA;
lenDif = - lenDif;
}
// 先在长链表上走lenDif步
for(int i = 0; i < lenDif; i++) {
headLong = headLong.next;
}
// 同时在两个链表上遍历
while( headLong != null && headShort != null) {
if(headLong == headShort)
return headLong;
headLong = headLong.next;
headShort = headShort.next;
}
return null;
}
private int getListLength(ListNode head) {
int count = 0;
while(head!=null) {
++count;
head = head.next;
}
return count;
}
}
双指针
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pA = headA;
ListNode pB = headB;
if(pA == null || pB == null) return null;
while(pA !=null || pB != null){
if(pA == null)
pA = headB;
else if(pB == null)
pB = headA;
if(pA == pB)
return pA;
pA = pA.next;
pB = pB.next;
}
return null;
}
}