Java环形链表

1.题目

环形链表:给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
环形链表

2.分析

在这里插入图片描述

fast!=null和fast.next!=null,fast就走两步,slow就走一步,每次走完就比较,相等就返回true,否则继续走,直到循环退出都没找到j就返回alse。
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

3.代码

 //判断环形链表
    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) {
    
    //相遇了
                break;
            }
        }
        if (fast == null || fast.next == null) {
    
    
            return false;
        }
        return true;
    

}

 //创建一个环
    public void createLoop() {
    
    
        ListNode cur = this.head;

        while (cur.next != null) {
    
    
            cur = cur.next;
        }
        cur.next = head.next.next;
    }

测试:

public static void main(String[] args) {
    
    
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addLast(12);
        myLinkedList.addLast(23);
        myLinkedList.addLast(34);
        myLinkedList.addLast(45);
        myLinkedList.addLast(56);
        System.out.println("myLinkedList:");
        myLinkedList.display();
        myLinkedList.createLoop();
        System.out.println(myLinkedList.hasCycle());
    }

注意:测试判断是否有环去掉参数,用自己的,但是力扣上面要加参数。

在这里插入图片描述

 public static void main(String[] args) {
    
    
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addLast(12);
        myLinkedList.addLast(23);
        myLinkedList.addLast(34);
        myLinkedList.addLast(45);
        myLinkedList.addLast(56);
        System.out.println("myLinkedList:");
        myLinkedList.display();
        //myLinkedList.createLoop();
        System.out.println(myLinkedList.hasCycle());
    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44721738/article/details/121191680