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

判断链表中是否有环

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

题目中说明每个节点的值|val|<=100000的,所以我们只需要遍历一遍链表,将每个遍历过的节点的val值设置为一个大于100000的值,每遍历到一个节点就判断当前节点的的next的val的绝对值是否大于100000,如果大于的话说明是之前遍历过的节点,则存在环。

/**
 * 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) {
        int max = 100000;
        if(head == null || head.next == null)
            return false;
        while(head != null){
            if(head.next != null && (head.next.val > max || -head.next.val > max))
                return true;
            head.val = max+1;
            head = head.next;
        }
        return false;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务