1. Given a list, the list is determined whether there is a ring (as defined in the two references, the speed of the pointer, will eventually meet)
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast=head;
ListNode slow=head;
do{
if(fast==null)
{
return false;//空链表
}
fast=fast.next;
if(fast==null)
return false;//无环链表
slow=slow.next;
fast=fast.next;
}while(fast!=slow);//知道他两相等,代表相遇,即有环
return true;
}
}
2. Given a list, the list starts to return into the first ring node. If chain acyclic, it is returned null
. (Define two references, a starting from scratch, starting from the meeting point to another, while walking, the first entry node is the point of encounter of the ring)
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast=head;
ListNode slow=head;
do{
if(fast==null)
{
return null;//空链表
}
fast=fast.next;
if(fast==null)
return null;//无环链表
slow=slow.next;
fast=fast.next;
}while(fast!=slow);//知道他两相等,代表相遇,即有环
ListNode p=head;//p从头出发
ListNode q=slow;//q从相遇结点出发
while(p!=q)
{
p=p.next;
q=q.next;
}
return p;
}
}
3. The sum of two intersection nodes of the list (the length of the two lists are determined, the definition of two reference points two lists, wherein a step difference go list of references, and then go together, if they are same, represents the intersection )
public class Solution {
private int getLength(ListNode head){
int len=0;
for(ListNode cur=head;cur!=null;cur=cur.next)
{
len++;
}
return len;
}//遍历求结点数
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lena=getLength(headA);//链表a的结点数
int lenb=getLength(headB);//链表b的结点数
int diff=lena-lenb;//结点数差
ListNode longer=headA;
ListNode shorter=headB;
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;
}
}