标签:
Intersection of Two Linked Lists
问题:
Write a program to find the node at which the intersection of two singly linked lists begins.
思路:
追击问题
我的代码:
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null) return null; int m = 0; ListNode startA = headA; ListNode startB = headB; while(headA.next != null) { headA = headA.next; m++; } int n = 0; while(headB.next != null) { headB = headB.next; n++; } if(headA != headB) return null; if(m > n) { int gap = m - n; for(int i = 0; i < gap; i++) { startA = startA.next; } } else { int gap = n - m; for(int i = 0; i < gap; i++) { startB = startB.next; } } while(startA != startB) { startA = startA.next; startB = startB.next; } return startA; } }
Intersection of Two Linked Lists
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4330812.html