题目描述
判断给定的链表中是否有环
扩展:
你能给出空间复杂度的解法么?
解题思路:
此题主要考察快慢指针, 快指针走两步,慢指针走一步,若链表存在环,则指针必相遇
终止条件null;
下面分别给出java 和C代码
/**
* 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||head.next==null||head.next.next==null){
return false;
}
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;
}
}
```java
```c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
#include<stdbool.h>
bool hasCycle(struct ListNode* head ) {
struct ListNode* fast=head;
struct ListNode *slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast == slow)return 1;
}
return 0;
}