LeetCode – 141. Linked List Cycle

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

Follow up:
Can you solve it without using extra space?

Using two pointers, one fast and one slow, they will definitely intersect if there is a cycle.

/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; fast.next.next != null){ slow =slow.next; fast = fast.next.next; if(slow == fast){ return true; } } return false; } }

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:「LeetCode – 141. Linked List Cycle」

192
0 0 192

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top