首页 > 其他 > 详细

链表遍历

时间:2019-12-26 18:55:13      阅读:76      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!