目录
3.给定一个链表,返回链表开始入环的第一个节点,若无则返回null
下面是两个相交的链表
此时要找两个链表的相交节点非常简单
只需要将两个链表的头节点分别向后移
当head1 == head2 时说明改节点是它们的相交节点
但当两个链表长度不一样的时候就会出现问题
遇到这种情况,一般会先求出两个链表的长度len1与len2,让长的那个链表走两链表的差值步(len1-len2)/(len2 - len1)
之后走相同步数直至相遇
代码示例:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode cur1 = headA;
ListNode cur2 = headB;
int count1 = 0;
int count2 = 0;
while (cur1.next != null) {
count1++;
cur1 = cur1.next;
}
cur1 = headA;
while (cur2.next != null) {
count2++;
cur2 = cur2.next;
}
cur2 = headB;
int dif = 0;
if (count1 >= count2) {
dif = count1 - count2;
while (dif != 0) {
cur1 = cur1.next;
dif--;
}
} else {
dif = count2 - count1;
while (dif != 0) {
cur2 = cur2.next;
dif--;
}
}
while (cur1 != cur2) {
cur1 = cur1.next;
cur2 = cur2.next;
}
if (cur1 == cur2) {
return cur1;
} else {
return null;
}
}
}
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
}
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
return null;
}
}
?