标签:ret length int == cti 相交 相同 没有 while
问题一:返回两个链表的相交结点问题二:判断链表是否带环
1.定义两个快慢指针,快指针先走两步,慢指针再走一步。直到快慢指针当前结点相同。 如果快指针先为null,则表示没有环,返回null。
2.如果带环,让起点和相遇点同时出发。同走一步,再判断相等与否,如果相等退出循坏 返回这个结点
```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;
}
}
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;
}
return p;
}
}
标签:ret length int == cti 相交 相同 没有 while
原文地址:https://blog.51cto.com/14232658/2444330