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?

题意:

判断一个链表是否有环。

解决方案:

双指针,快指针每次走两步,慢指针每次走一步,

如果有环,快指针和慢指针会在环内相遇,fast == slow,这时候返回true。

如果没有环,返回false.

/**
* 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) {
ListNode fast = head, slow = head;
if(head == null || head.next == null) return false; while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next; if(fast == slow){
return true;
}
} return false;
}
}
上一篇:Python第九课学习


下一篇:20181015记录一个简单的TXT日志类