leetcode打卡day9

主宰稳场 提交于 2020-03-09 21:52:00

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

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

执行结果:通过
执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :41.3 MB, 在所有 Java 提交中击败了5.02%的用户

思路:当 head.next 不为空时,将head.next 指向 head.next.next,相当于去掉了next节点,到最后如果有环,head == head.next。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!