链表遍历

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;
}

 

posted @ 2019-12-26 18:36  阿柒~  阅读(438)  评论(0编辑  收藏  举报