- 题目描述:判断一个链表是否有循环
- 思路:
- 定义快慢指针,慢指针走一步,快指针走两步,若两者能相遇,则有循环
- 或者用java里的哈希表,把每个节点的引用存入表中,若访问节点在表中存在则有循环,若因为指针指向空而退出,自然安不存在循环
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *slow=head;
struct ListNode *fast=head;
if(!head){
return NULL;
}
while(fast->next!=NULL&&fast->next->next!=NULL){//若是有循环,那么快指针是不会为空的
slow=slow->next;//慢指针走一步
fast=fast->next->next;//快指针走两步
if(slow==fast){//当两者会相遇,说明有循环
return true;
}
}
return 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) {
Set<ListNode> set=new HashSet<>();
while(head!=null){
if(set.contains(head)){
return true;
}else{
set.add(head);
}
head=head.next;
}
return false;
}
}