其他分享
首页 > 其他分享> > 【2022初春】【LeetCode】141. 环形链表

【2022初春】【LeetCode】141. 环形链表

作者:互联网

自己写的诡异方法

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

链表双指针常见问题
双指针:链表第K个元素,链表中间元素,环形链表
本题可以用双指针,两个指针相遇了即为有环

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

标签:head,ListNode,val,141,fast,next,链表,2022,null
来源: https://blog.csdn.net/mdzz_z/article/details/122750566