LeetCode题解:Linked List Cycle

来源:互联网 发布:网络博客代理 编辑:程序博客网 时间:2024/06/11 22:43

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

题意:给定链表,判断是否为环。要求O(1)空间

思路:快慢指针,如果存在环,快指针必然遇到慢指针

代码:

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

0 0