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

 

相关文章:

  • 2022-12-23
  • 2021-10-11
  • 2021-12-11
  • 2021-12-19
  • 2021-08-16
  • 2021-11-24
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-23
  • 2022-01-13
  • 2019-06-19
  • 2022-12-23
相关资源
相似解决方案