[LeetCode]No.141 Linked List Cycle

链接:https://leetcode.com/problems/linked-list-cycle/
原题:
Given a linked list, determine if it has a cycle in it.

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

分析:这道题的意思是在不开辟另外内存空间的情况下 判断是否是循环的链表
这里用两个游标用来做比较,一个是一个跳两个节点,一个是一次跳一个节点,如果是循环链表,两个游标肯定有重合的时候

/**
 * 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;
        while (true) {
            if(fast == null || slow== null) {
                return false;
            }
            fast = fast.next;
            if(slow.next!=null) {
               slow = slow.next.next;
            } else {
                return false;
            }
            if(fast == slow) {
                return true;
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容