您的位置:首页 > 其它

LeetCode 141 Linked List Cycle题解

2016-12-05 21:00 429 查看
题目地址:https://leetcode.com/problems/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?

是否可以不使用额外空间解决问题?

算法设计:

快慢指针法,快慢指针一开始都指向头部,快指针每次走两步,慢指针每次走一步,如果快指针指向null之前,追上了慢指针那么链表中存在循环

Java代码实现:

/**
* 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)
return false;
ListNode slow=head;
ListNode fast=head;
while(true)
{
fast=fast.next;
if(fast==null)
return false;
if(fast==slow)
return true;
fast=fast.next;
if(fast==null)
return false;
if(fast==slow)
return true;
slow=slow.next;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: