Last active
August 29, 2015 14:22
-
-
Save cangoal/6813a0544496e211acf2 to your computer and use it in GitHub Desktop.
LeetCode - Intersection of Two Linked Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| public ListNode getIntersectionNode(ListNode headA, ListNode headB) { | |
| if(headA == null || headB == null) return null; | |
| ListNode h1 = headA, h2 = headB; | |
| while(headA != null && headB != null){ | |
| if(headA == headB) return headA; | |
| headA = headA.next; | |
| headB = headB.next; | |
| if(headA == null && headB == null) return null; | |
| if(headA == null) headA = h2; | |
| if(headB == null) headB = h1; | |
| } | |
| return null; | |
| } | |
| // | |
| public ListNode getIntersectionNode(ListNode headA, ListNode headB) { | |
| if(headA == null || headB == null) return null; | |
| ListNode p = headA, q = headB; | |
| boolean flag1 = false, flag2 = false; | |
| while(p != null && q != null){ | |
| if(p == q) return p; | |
| p = p.next; | |
| q = q.next; | |
| if(p == null){ | |
| if(flag1) break; | |
| p = headB; | |
| flag1 = true; | |
| } | |
| if(q == null){ | |
| if(flag2) break; | |
| q = headA; | |
| flag2 = true; | |
| } | |
| } | |
| return null; | |
| } | |
| // | |
| public ListNode getIntersectionNode(ListNode headA, ListNode headB) { | |
| if(headA==null || headB==null) return null; | |
| ListNode pA = headA, pB=headB, tailA = null, tailB=null; | |
| while(true){ | |
| if(pA==null) | |
| pA = headB; | |
| if(pB==null) | |
| pB = headA; | |
| if(pA.next==null) | |
| tailA = pA; | |
| if(pB.next==null) | |
| tailB = pB; | |
| if(tailA!=null&&tailB!=null&tailA!=tailB) | |
| return null; | |
| if(pA==pB) | |
| return pA; | |
| pA = pA.next; | |
| pB = pB.next; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment