判断单链表是否带环(某公司实习生招聘笔试试题)
2012-10-19 20:29
295 查看
#include<iostream> using namespace std; typedef struct node { int data; struct node *next; }Node; Node *createList(int n) { Node *p = new Node ; for( int i = 1; i < n; ++i) { p[i - 1].next = &p[i]; p[i - 1].data = i; } p[n - 1].next = NULL; p[n - 1].data = n; return p; } Node *createListWithRing(int n) { Node *p = new Node ; for( int i = 1; i < n; ++i) { p[i - 1].next = &p[i]; p[i - 1].data = i; } p[n - 1].next = &p[n/2]; p[n - 1].data = n; return p; } //pFast相当于摩托车,pSlow相当于自行车 //摩托车在前,自行车在后,如果还能相遇,则必然有环 bool listHasRing(Node *p) { Node *pSlow = &p[0]; Node *pFast = &p[1]; while(NULL != pSlow && NULL != pFast -> next) { if(pSlow == pFast) return true; pSlow = pSlow -> next; pFast = pFast -> next ->next; } return false; } void print(bool b) { if(b) cout << "There is a ring in the list." << endl; else cout << "There is no ring in the list." << endl; } int main() { int n = 10; Node *head = createList(n); print(listHasRing(head)); delete [] head; head = createListWithRing(10); print(listHasRing(head)); delete [] head; return 0; }
相关文章推荐
- 如何判断两个矩形是否有重叠部分?(某公司校园招聘笔试试题)
- 如何判断两个矩形是否有重叠部分?(某公司校园招聘笔试试题)
- 判断表达式中括号是否匹配(栈的典型应用)(某公司校园招聘笔试试题)
- 数据库表删除之drop table xxx (某公司实习生招聘笔试试题)
- 聊聊这个与代码优化有关的选择题 (某公司实习生招聘笔试试题)
- 任务调度时间 (某公司实习生招聘笔试试题)
- 笔试,面试,C/C++,判断单链表是否带环?若带环,求环长度,求环入口点(两种方法)
- 聊聊这个与代码优化有关的选择题 (某公司实习生招聘笔试试题)
- 简单详解:x^6+4x^4+2x^3+x+1 至少要需要多少次乘法? (某公司实习生招聘笔试试题)
- 用递归方法对二叉树进行层次遍历(某公司实习生招聘笔试试题)
- int a1=x+y-z; int a2=x-z+y; a1和a2的值一定相等吗? (某公司实习生招聘笔试试题)
- 笔试,面试,C/C++,判断单链表是否带环?若带环,求环长度,求环入口点(两种方法)
- Little's Law(利特尔法则)的简要证明和重要应用(2012年某公司实习生招聘笔试试题)
- 如何判断平面上两条线段(注意是线段)是否相交?(某公司校园招聘面试试题)
- 再谈IPC之共享内存 (某公司实习生招聘笔试试题)
- 时间复杂度为O(n)来判断数组a[N](1 <= a[i] <= N)中是否有重复元素 (某公司校园招聘笔试题目)
- Little's Law(利特尔法则)的简要证明和重要应用(2012年某公司实习生招聘笔试试题)
- 又见组合数, 好亲切! (某公司实习生招聘笔试试题)
- 华为2017实习生招聘笔试题-公司年会
- 骇人听闻的二分查找(某公司校园招聘笔试试题)(据说只有10%的程序员可以写出没有bug的二分查找)