[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?

题意:

给定一个链表,判断是否循环

思路:

快慢指针

若有环,则快慢指针一定会在某个节点相遇(此处省略证明)

[leetcode]141. Linked List Cycle判断链表是否有环

代码:

 public class Solution {
public boolean hasCycle(ListNode head) {
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;
}
}
上一篇:2017普及组D1T3 洛谷P3956 棋盘


下一篇:洛谷 P2058 海港 解题报告