【Leetcode-Easy-141】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) {
if (head == null || head.next == null) return false;
ListNode quick = head;
ListNode slow = head;
while (quick != null && slow != null){
if (quick.next != null) quick = quick.next.next;
else return false;
slow = slow.next;
if (quick == slow) return true;
}
return false;
}
}

本文介绍了一种使用快慢指针的方法来判断链表是否存在环。这种方法不需要额外的空间,通过两个速度不同的指针遍历链表,如果存在环则快指针最终会追上慢指针。
3566

被折叠的 条评论
为什么被折叠?



