基本思路:
如果链表有环,那么在遍历链表时则会陷入死循环,利用这个特征,我们可以设计这样的算法。
public boolean hasCycle(ListNode head) { ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (fast == slow) { return true; } } return false; }
public ListNode detectCycle(ListNode head) { ListNode slow = head.next; ListNode fast = head.next.next; while(slow!=fast){ if (slow.next==null||fast.next.next==null){ return null; } slow=slow.next; fast=fast.next.next; } fast=head; while (slow!=fast){ slow=slow.next; fast=fast.next; } return slow; }
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode cur1=headA; ListNode cur2=headB; int n=0; while (cur1!=null){ n++; cur1=cur1.next; } while (cur2!=null){ n--; cur2=cur2.next; } if (cur1!=cur2){ return null; } cur1=n>0?headA:headB;//把长的链表赋给cur1 cur2=cur1==headA?headB:headA;//判断cur1是否是headA这个链表,如果是,将 n=Math.abs(n); while (n!=0){ n--; cur1=cur1.next; } while (cur1!=cur2){ cur1=cur1.next; cur2=cur2.next; } return cur1; }
public ListNode bothLoop(ListNode head1,ListNode loop1,ListNode head2,ListNode loop2){ ListNode cur1=null; ListNode cur2=null; if (loop1==loop2){ cur1=head1; cur2=head2; int n=0; while (cur1!=null){ n++; cur1=cur1.next; } while (cur2!=null){ n--; cur2=cur2.next; } if (cur1!=cur2){ return null; } cur1=n>0?head1:head2; cur2=cur1==head1?head2:head1; n=Math.abs(n); while (n!=0){ n--; cur1=cur1.next; } while (cur1!=cur2){ cur1=cur1.next; cur2=cur2.next; } return cur1; }else{ cur1=loop1.next; while(cur1!=loop1){ if (cur1==loop2){ return loop1; } cur1=cur1.next; } return null; } }