/* 判断单链表是否存在环
1)暴力:双层循环遍历(n^2) 2)双指针:快指针fast=NULL,慢指针slow=NULL int judge(link head) { if(NULL==head) return false; link fast = head, slow = head; while(slow!=NULL && fast!=NULL) { slow = slow->next; fast = fast->next->next; if(slow==fast) { return true; } } return false; }
计算带环单链表的长度
int count(link head) { if(NULL==head) return false; link fast = head, slow = head; while(slow!=NULL && fast!=NULL) { slow = slow->next; fast = fast->next->next; if(slow==fast) { flag = true; break; } } if(flag) { int ans = 1; slow = slow->next; while(slow!=fast) { ans++; slow = slow->next; } return ans ; } return false; }
查找单链表中环的入口
设环长为n,非环形部分长度为m link find(link head) { int flag = false; if(NULL==head) return false; link fast = head, slow = head; while(slow!=NULL && fast!=NULL) { slow = slow->next; fast = fast->next->next; if(slow==fast) { flag=true; break; } } if(flag) { slow = head; while(slow!=fast) { slow = slow->next; fast = fast->next; } return slow; } return NULL; }
原文地址:https://www.cnblogs.com/Shallow-dream/p/11767269.html
时间: 2024-10-13 23:49:18