题解 | #判断链表中是否有环#

判断链表中是否有环

http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null){
            return false;
        }
        //设置两个指针,一个一步走一个节点,一个一步走两个节点,如果有环,二者会相等的时候,如果无环,二者会有一个先为null
        ListNode first = head;
        ListNode second = head;
        do {
            first = first.next;
            if(second.next != null){
                second = second.next.next;
            }else {
                return false;
            }
        }while (first != null && second != null && first != second);
        //步频不同,如果有一个为null 肯定不等
        return first == second;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
10-15 09:13
已编辑
天津大学 soc前端设计
点赞 评论 收藏
分享
YZBPXX:国科的佬都挂了 让我们这些四非怎么活呀
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务