問題一:返回兩個鏈表的相交結點
1.先分別獲得兩個鏈表的長度
2.獲得長度差,
3.先讓長鏈表的頭結點走(長度差)步。
4.這時。短鏈表頭結點還在原地,二者開始一塊兒走,當獲得二者val相等時,這個結點就是公共結點,即相遇結點。ide
```public class Solution {
private int getLength(ListNode head) {
int len = 0;
for (ListNode c = head; c != null; c = c.next) {
len++;
}指針
return len; } public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int lenA = getLength(headA); int lenB = getLength(headB); ListNode longer = headA; ListNode shorter = headB; int diff = lenA - lenB; if (lenA < lenB) { longer = headB; shorter = headA; diff = lenB - lenA; } for (int i = 0; i < diff; i++) { longer = longer.next; } while (longer != shorter) { longer = longer.next; shorter = shorter.next; } return longer; }
}code
問題二:判斷鏈表是否帶環 1.定義兩個快慢指針,快指針先走兩步,慢指針再走一步。直到快慢指針當前結點相同。 若是快指針先爲null,則表示沒有環,返回null。 2.若是帶環,讓起點和相遇點同時出發。同走一步,再判斷相等與否,若是相等退出循壞 返回這個結點
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
// fast 遇到 null,表示不帶環,返回 null
// fast == slow,表示遇到相遇點了
do {
if (fast == null) {
return null;
}
fast = fast.next;
if (fast == null) {
return null;
}
fast = fast.next;
slow = slow.next;
} while (fast != slow);
// 求相遇點
// 若是快的遇到 null,表示沒有環,直接返回 null
// 相遇點出發 + 起點出發,最終相遇
ListNode p = head;
ListNode q = slow;
while (p != q) {
p = p.next;
q = q.next;
}get
return p; }
}it