LeetCode热题100道-Day06

60 阅读1分钟

LeetCode热题100道-Day06

141. 环形链表

  • 使用快慢指针,快指针每次前进两个单位,慢指针前进一个单位,如果是环,最终会相遇。
/**
 * 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) {
        ListNode fast = head;
        ListNode slow = head;
        if(head == null){
            return false;
        }
        while(true){
            if(fast.next == null || fast.next.next ==null){
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                return true;
            }
        }
    }
}
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func hasCycle(head *ListNode) bool {
    if head == nil {
        return false
    }
    fast := head
    slow := head
    for ;; {
        if fast.Next == nil || fast.Next.Next == nil {
            return false
        }
        fast = fast.Next.Next
        slow = slow.Next
        if fast == slow{
            return true
        }
    }
}