牛客题霸NC4(判断链表是否有环)

判断给定的链表中是否有环
扩展:
你能给出空间复杂度的解法么?
牛客题霸NC4

 使用快,慢指针可以无需额外空间,慢指针一次走一步,快指针一次走两步,若有环,两者必相遇,因为两者会在一个圈里面循环跑,一快一慢,快指针肯定会套圈(可以想象100000000000000000000000000000米田径赛跑,实力相差悬殊的情况下会出现套圈的现象)

/**
 * 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){
            return false;
        }
        ListNode slow = head,fast = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }
}
View Code

 还有一个方法是使用LinkedList保存已出现的节点,每遍历一个节点就判断一下是否在LinkedList中出现过,代码略

2020/10/09leetcode的每日一题,题解写法

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         if (head == null || head.next == null) {
 4             return false;
 5         }
 6         ListNode slow = head;
 7         ListNode fast = head.next;
 8         while (slow != fast) {
 9             if (fast == null || fast.next == null) {
10                 return false;
11             }
12             slow = slow.next;
13             fast = fast.next.next;
14         }
15         return true;
16     }
17 }
View Code

 

posted @ 2020-08-25 16:56  雨下_整夜  阅读(192)  评论(0)    收藏  举报