标签:return ret ast 方式 cycle poi next linked public
141. Linked List Cycle (环形链表)
题目概述:判断一个链表中是否有环
思路
创建两个指针(快指针和慢指针),慢指针的移动方式为:单次移动一个结点;快指针的移动方式为:单次移动两个结点。如果快指针指向的结点和慢指针指向的结点相同(注:这里的结点指向了对象,所以直接通过==判断是否为同一结点),则该链表有环。
代码实现
/** * 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 slowPointer = head; ListNode fastPointer = head; while (slowPointer != null && fastPointer != null && fastPointer.next != null) { slowPointer = slowPointer.next; fastPointer = fastPointer.next.next; if (slowPointer == fastPointer) {return true;} } return false; } }
标签:return ret ast 方式 cycle poi next linked public
原文地址:https://www.cnblogs.com/mrjoker-lzh/p/9774705.html