Linked List Cycle

项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步

Given a linked list, determine if it has a cycle in it.

原题是判断一个链表是否有环。我们给加大难度,找出环的起点。

判断链表是否有环比较简单。设置两个快慢指针,分别从链表的头节点出发,慢指针每次向后移动一步,快指针移动两步。如果链表存在环,快慢指针一定会在环里相遇。

求环入口位置具体逻辑见代码。

public class LinkedListCycle {

    public static Node init_linkedlist() {
        Node head = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);

        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node1;

        return head;
    }

    public static Node hasCycle(Node head) {
        Node slow = head;
        Node fast = head;

        //如果相遇,说明有环
        while(slow != null && fast != null) {
            slow = slow.next;
            fast = fast.next.next;

            if(slow == fast) {
                System.out.println("There is a cycle!");
                break;
            }
        }

        //找环的入口
        slow = head;
        while(slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }

        return fast;
    }

    public static void main(String[] args) {
        Node head = init_linkedlist();
        Node cycle_first = hasCycle(head);
        System.out.println(cycle_first.val);
    }

}

class Node {
    int val;
    Node next;

    public Node(int val) {
        this.val = val;
        this.next = null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值