关于链表中是否带环和找到环的入口点

来源:互联网 发布:cf刷枪软件 编辑:程序博客网 时间:2024/06/05 19:15

面试题一:判断链表是否带环

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:18px;"><strong style="background-color: rgb(255, 255, 255);">int FndLoop(pLinkList list)  
  2. {  
  3. pLinkNode fast=list->pHead;  
  4. pLinkNode slow=list->pHead;  
  5. assert(list);  
  6. while(fast!=NULL && fast->next!=NULL)  
  7. {  
  8. slow=slow->next;  
  9. fast=fast->next->next;  
  10. if( fast!=NULL && slow==fast)  
  11. {  
  12. return 1;//有环  
  13. }  
  14. }  
  15. return 0;//无环  
  16. }</strong></span>  

面试题二:找到环的入口点

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:18px;"><strong>pLinkNode FndLoopNode(pLinkList list)  
  2. {  
  3. pLinkNode fast=list->pHead;  
  4. pLinkNode slow=list->pHead;  
  5. assert(list);  
  6. while(fast!=NULL && fast->next!=NULL)  
  7. {  
  8. slow=slow->next;  
  9. fast=fast->next->next;  
  10. if( fast!=NULL && slow==fast)  
  11. {  
  12. break;  
  13. }  
  14. }  
  15. slow=list->pHead;  
  16. while(slow!=fast)  
  17. {  
  18. slow=slow->next;  
  19. fast=fast->next;  
  20. }  
  21. return slow;  
  22. }</strong></span>  
阅读全文
0 0