標籤:def ret link lse tin 交點 linked 時間複雜度 solution
編寫一個程式,找到兩個單鏈表相交的起始節點。
例如,下面的兩個鏈表:
A: a1 → a2 c1 → c2 → c3 B: b1 → b2 → b3
在節點 c1 開始相交。
注意:
- 如果兩個鏈表沒有交點,返回
null.
- 在返回結果後,兩個鏈表仍須保持原有的結構。
- 可假定整個鏈表結構中沒有迴圈。
- 程式盡量滿足 O(n) 時間複雜度,且僅用 O(1) 記憶體。
/** * 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) { if (headA == null || headB == null) { return null; } int lenA = len(headA); int lenB = len(headB); if (lenA>lenB) { while (lenA != lenB) { headA = headA.next; lenA--; } } else { while (lenA != lenB) { headB = headB.next; lenB--; } } while (headA != headB) { headA = headA.next; headB = headB.next; } return headA; } private int len(ListNode headA) { int len = 0; while (headA != null) { headA = headA.next; len++; } return len; }}
LeetCode160.相交鏈表