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 n= head, p=head;
while (n.next != null){
if (n.next== head) return true;
n= n.next;
p.next= head;
p= n;
}
return false;
}
}
本文介绍了一种检测链表中是否存在循环的方法。通过遍历链表并利用特定节点标记的方式,可以有效判断链表是否包含循环结构。此外,还提供了一个不使用额外空间的解决方案。

242

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



