LeetCode 141 Linked List Cycle题解
2016-12-05 21:00
429 查看
题目地址:https://leetcode.com/problems/linked-list-cycle/
给定一个链表,找出链表中是否存在循环
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)
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;
}
}
}
题目:
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;
}
}
}
相关文章推荐
- [LeetCode]题解(python):141-Linked List Cycle
- LeetCode 141 Linked List Cycle(链表判环)
- leetcode 141-Linked List Cycle
- leetcode 141: Linked List Cycle
- leetcode 141: Linked List Cycle
- leetcode_141题——Linked List Cycle (set)
- LeetCode 141 Linked List Cycle
- LeetCode题解——Linked List Cycle II
- LeetCode(141)——Linked List Cycle
- [LeetCode-141] Linked List Cycle(判断链表是否有环)
- LeetCode 141 Linked List Cycle和142 Linked List Cycle II
- leetcode(141):Linked List Cycle
- Leetcode_141_Linked List Cycle
- LeetCode 141: Linked List Cycle
- [LeetCode]: 141: Linked List Cycle
- leetcode || 141、Linked List Cycle
- Leetcode141——Linked List Cycle
- LeetCode 141 — Linked List Cycle(C++ Java Python)
- 【leetcode】141/142Linked List Cycle(Floyd判圈算法)
- [LeetCode]141 Linked List Cycle