码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode 141题 环形链表(Linked List Cycle) Java语言求解

时间:2020-01-24 09:27:15      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:代码   地址   uip   循环   init   link   cycle   put   相同   

题目描述:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

Map集合解法

思路:
创建一个map集合,key为节点,value为地址值,因为ListNode没有重写toString()方法,所以用toString()方法返回的内容作为value。
如果map中存在当前节点的toString()方法返回的内容,则存在环。

/**
 * 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){
            return false;
        }
        Map<ListNode,String> map = new HashMap<ListNode,String>();
        while(head != null){
            if(map.containsValue(head.toString())){
                return true;
            }
            else{
                map.put(head,head.toString());
                head = head.next;
            }
        }
        return false;
    }
}

提交结果截图:
技术图片
技术图片

快慢指针解法

技术图片
分析:
将slow指针指向head;
将fast指针指向head.next;
在循环的过程中slow走一步,fast走两步,如果存在环,则slow和fast一定会相遇,如本例子中:slow在1处,fast在2处;然后slow走一步,到2处,fast走两步,到4处;slow到3处,fast到3处,slow和fast相遇。
代码如下:

/**
 * 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)
            return false;
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != null){
            if(slow == fast){
                return true;
            }
            slow = slow.next;
            fast = fast.next;
            if(fast != null)
                fast = fast.next;
        }
        return false;
    }
}

对代码的解释:
1、如果head为空,则不是环,返回false;
2、如果fast不为空,则进入循环体;否则退出循环,无环,返回false;
3、如果slow和fast指向的节点相同,则存在环,返回true;
4、slow向后移动一个节点;
4、fast向后移动一个节点,如果fast不为空,再向后移动一个节点(不能直接移动两个节点,否则会报空指针异常);转2。
提交结果截图:
技术图片
技术图片
由图可知,快慢指针方法更好一些。

欢迎关注

扫下方二维码即可关注:
技术图片

Leetcode 141题 环形链表(Linked List Cycle) Java语言求解

标签:代码   地址   uip   循环   init   link   cycle   put   相同   

原文地址:https://www.cnblogs.com/nicaicai/p/12231849.html

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