链表遍历

1.快速找到链表的中间节点

public ListNode findMedium(ListNode head){
    if(head == null || head.next == null)
        return head;
    
    ListNode s1 = head, s2 = head.next;

    while(s2 != null && s2.next != null){
        s1 = s1.next;
        s2 = s2.next.next;
    }     
    
    return s1.next;
}

2.判断链表中是否存在环

public boolean hasCircle(ListNode head){
    if(head == null)
        return false;
    
    ListNode s1 = head, s2 = head.next;

    while(s2 != null && s2.next != null){
        if(s1 == s2)
            return true;  
        s1 = s1.next;
        s2 = s2.next.next;
    }     
    
    return false;
}
原文地址:https://www.cnblogs.com/qwer112/p/12103769.html