码迷,mamicode.com
首页 > 其他好文 > 详细

141. Linked List Cycle

时间:2018-10-11 22:01:19      阅读:163      评论:0      收藏:0      [点我收藏+]

标签: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;
    }
}

 

141. Linked List Cycle

标签:return   ret   ast   方式   cycle   poi   next   linked   public   

原文地址:https://www.cnblogs.com/mrjoker-lzh/p/9774705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!