【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;
    }
}
上一篇:01月31日假期学习


下一篇:【Leetcode刷题笔记之链表篇】141. 环形链表