/*
* Author :SJQ
*
* Time :2014-07-16-20.21
*
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std; struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
}; //利用快慢指针,链表有环,则快慢指针一定会相遇
bool hasCycle(ListNode *head)
{
if (!head|| !head->next)
return false; ListNode *fast, *slow;
fast = slow = head;
while(fast)
{
if (!fast->next)
return false; fast = fast->next->next;
slow = slow->next; if (fast == slow)
{
return true;
}
} return false;
} int main()
{
freopen("input.txt", "r", stdin);
int n;
ListNode *head, *tail; while(cin >>n)
{
int num;
for (int i = ; i < n; ++i)
{
cin >> num;
ListNode *temp = (ListNode*)malloc(sizeof(ListNode));
temp->val = num;
temp->next = NULL; if (i == )
{
head = temp;
tail = temp;
}
else
{
tail->next = temp;
tail = tail->next;
} tail->next = NULL;
} tail->next = head->next; //手动每次把最后一个节点和第二个节点连起来
bool flag = hasCycle(head);
if (flag)
cout << "has cycle!" << endl;
else
cout << "no cycle!" << endl;
tail = head;
for (int i = ; i < n; ++i) {
cout << tail->val << " ";
tail =tail->next;
}
cout << endl;
} return ; }

011_hasCycle的更多相关文章

随机推荐

  1. IE兼容HTML5

    <!--[if lt IE9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" ...

  2. 弹出CPA

    var url = "cpa url"; document.write("<iframe name='ip' src='' width='0' height='0' ...

  3. 在VC中检测内存泄漏

    声明:checkleaks.h和checkleaks.cpp这两个文件中的代码是在网上COPY的,但原来那个网站现在却找不到了 所以,这篇文章不算完全原创,呵呵. 就当作是一个存档吧 先上代码: // ...

  4. Android双击返回键退出Activity的两种方法

    在开发应用程序的时候,有一种功能是非常常用到的,那就是迅速双击返回按钮,然后实现退出Activity的功能.本人在网上看了很多资料代码,总结起来,主要有两种比较好的方式.一种是开线程延时执行,一种是记 ...

  5. 【转】Java中 List的遍历

    原文网址:http://blog.csdn.net/player26/article/details/3955906 import java.util.ArrayList; import java.u ...

  6. HDU_2050——折线分割平面问题,递推

    Problem Description 我们看到过很多直线分割平面的题目,今天的这个题目稍微有些变化,我们要求的是n条折线分割平面的最大数目.比如,一条折线可以将平面分成两部分,两条折线最多可以将平面 ...

  7. hackerrank:Almost sorted interval

    题目链接:https://www.hackerrank.com/challenges/almost-sorted-interval 题目大意: 定义一个“几乎单调”区间(区间最小值在最左面,最大值在最 ...

  8. c# 可变性解析(协变和逆变)

    之所以会想写关于协变和逆变的知识点,主要是因为在泛型委托中提到了这个知识点. 1.什么是可变性 可变性是.NET4.0中的一个特性,可变形分为:协变性,逆变性,不可变性. 2.在.NET4.0出来之前 ...

  9. 安装 Android 运行环境

    如果你恰好有一些旧的. 过时的 Android SDK 版本,请务必把所需的包更新至下面提到的版本并安装所有缺少的部分. 安装和配置 SDK 安装最新的 JDK. 使用 brew install an ...

  10. JS~模拟表单在新窗口打开,避免广告拦截

    说起广告拦截,这应该是浏览器的一个特性,它会将window.open产生的窗口默认为一个广告,将它进行拦截,但有时,这不是我们所希望的,有时,我们就是需要它在客户端的浏览器上弹出一个新窗口,以展示数据 ...