141. Linked List Cycle (判断单链表中是否有环)

来源:互联网 发布:红米note只有2g网络 编辑:程序博客网 时间:2024/05/20 06:29

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

Follow up:

Can you solve it without using extra space?

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


0 0
原创粉丝点击