龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

程序员必看 c++笔试题汇总(1)(11)

时间:2011-04-12 23:18来源:未知 作者:admin 点击:
分享到:
45. 如何判断一个单链表是有环的?(注意不能用标志位,最多只能用两个额外指针) struct node { char val; node* next;} bool check(const node* head) {} //return false : 无环

45. 如何判断一个单链表是有环的?(注意不能用标志位,最多只能用两个额外指针)

struct node { char val; node* next;}

bool check(const node* head) {} //return false : 无环;true: 有环

一种O(n)的办法就是(搞两个指针,一个每次递增一步,一个每次递增两步,如果有环的话两者必然重合,反之亦然):

  1. bool check(const node* head)  
  2. {  
  3. if(head==NULL) return false;  
  4. node *low=head, *fast=head->next;  
  5. while(fast!=NULL && fast->next!=NULL)  
  6. {  
  7. low=low->next;  
  8. fast=fast->next->next;  
  9. if(low==fast) return true;  
  10. }  
  11. return false;   

本篇文章只是笔者个人对程序员c++笔试题的一些个人总结,如果大家对以上内容有不同见解,也欢迎留言告之。

精彩图集

赞助商链接