力扣练习题
141环形链表

题目分析及代码实现
我们利用双指针,其实是两个在链表中有不同遍历速度的指针,当快的指针与慢的指针可以指向同一个节点时,则链表中有环。
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public bool HasCycle(ListNode head) {
if (head == null || head.next == null)
{
return false;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null)//循环条件
{
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
{
return true;
}
}
return false;
}
}


这篇博客主要解析了力扣上的经典问题——141环形链表,通过使用双指针策略来判断链表中是否存在环。文章详细分析了题意,并给出了具体的代码实现。
833

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



