011_hasCycle
/*
* 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的更多相关文章
随机推荐
- mongodb工具
可视化管理工具 http://www.mongovue.com/ mongodb use case http://www.mongodb.org/about/applications/ mongodb ...
- 高性能web
http://developer.51cto.com/art/201104/255619.htm http://developer.51cto.com/art/201104/254031.htm ht ...
- Qt自定义带游标的slider,在滑块正上方显示当前值(类似于进度条,用一个额外的QLabel冒充QSilder的一部分,然后move就行了)
首先自定义QSlider的子类MyCustomSlider,如下所示. mycustomslider.h #ifndef MYCUSTOMSLIDER_H #define MYCUSTOMSLIDER ...
- delphi 程序窗体及控件自适应分辨率(通过ComponentCount遍历改变字体大小以及上下左右)
unit untFixForm; interface uses Classes, SysUtils, Controls, Forms; type TFontedControl = class(TCon ...
- 分布式文件系统 FastDFS Ceph
分布式文件系统 FastDFS Cephhttp://www.oschina.net/p/fastdfshttp://www.oschina.net/p/ceph FastDFS 的 Go 客户端 f ...
- Stack Overflow requires external JavaScript from another domain, which is blocked or failed to load.
出现以上问题,只是说明stackoverflow前端库用到google的API来,所以stackoverflow躺枪.查阅后,是因为调用jquery的问题. 详情请看: 解决方案有好几种: 1.将ht ...
- 转载-常用API接口签名验证参考
原文地址: http://www.cnblogs.com/hnsongbiao/p/5478645.html 写的很好,就做个笔记了.感谢作者! 项目中常用的API接口签名验证方法: 1. 给app分 ...
- Storm概念介绍
Storm核心概念如下: 1.Tuple:元组 Tuple即元组,是一个拓扑Topology中的Spout和Bolt组件之间数据传递的基本单元.元组中的字段可以是任何类 ...
- uva 10714 Ants(贪心)
题目连接:10714 - Ants 题目大意:一根棍子上有n只蚂蚁, 这些蚂蚁开始可以任意朝着一个方向移动一直走,向左或是向右,并且移动速度是相同的,但是一旦蚂蚁碰到迎面走来的另一只蚂蚁,那么这两只蚂 ...
- windows下定时利用bat脚本实现ftp上传和下载
前言: 工作中可能会遇到以下情况,利用windows作为中转,来实现两台linux服务器的文件传输. 实现步骤: 1.FTP上传和下载的bat脚本. 脚本分为两部分:可执行bat脚本和ftp命令文件: ...