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的更多相关文章
随机推荐
- 一个使用CSocket类的网络通信实例
http://www.cppblog.com/changshoumeng/archive/2010/05/14/115413.html 3.8 一个使用CSocket类的网络通信实例 本例采用CSoc ...
- IOS开发之免费证书+不越狱真机调试
本文转自:http://www.cnblogs.com/weii/p/4688299.html 苹果发布Xcode7后, 开放了普通的AppleID也能真机调试,非$99 或 $299, 只要能上 ...
- U-Boot启动过程完全分析
U-Boot启动过程完全分析 1.1 U-Boot工作过程 U-Boot启动内核的过程可以分为两个阶段,两个阶段的功能如下: (1)第一阶段的功能 硬件设备初始化 加载U-Boot第二阶段 ...
- orientationchange的兼容性
移动webapp监测屏幕旋转时常用onorientationchange事件,用此事件获取改变后的屏幕尺寸时需要注意: 1. iphone中,可立即获取改变后的屏幕尺寸. 2. android中,获取 ...
- windows环境变量如何在cmd中打印
在windows的cmd下,用"set"命令可以得到全部的环境变量,如何想得到某个环境变量,直接这样"set path"就可以了. set不仅如何,还有其他功能 ...
- 一道面试题与Java位操作 和 BitSet 库的使用
前一段时间在网上看到这样一道面试题: 有个老的手机短信程序,由于当时的手机CPU,内存都很烂.所以这个短信程序只能记住256条短信,多了就删了. 每个短信有个唯一的ID,在0到255之间.当然用户可能 ...
- POJ_3083——贴左右墙DFS,最短路径BFS
Description The cornfield maze is a popular Halloween treat. Visitors are shown the entrance and mus ...
- HDU_2044——蜜蜂走蜂房,递推
Problem Description 有一只经过训练的蜜蜂只能爬向右侧相邻的蜂房,不能反向爬行.请编程计算蜜蜂从蜂房a爬到蜂房b的可能路线数. 其中,蜂房的结构如下所示. Input 输入数据的 ...
- uva 10714 Ants(贪心)
题目连接:10714 - Ants 题目大意:一根棍子上有n只蚂蚁, 这些蚂蚁开始可以任意朝着一个方向移动一直走,向左或是向右,并且移动速度是相同的,但是一旦蚂蚁碰到迎面走来的另一只蚂蚁,那么这两只蚂 ...
- JS截取字符串方法
function textSubstr(str,sub_length){ str = str.trim(); var temp1 = str.replace(/[^\x00-\xff]/g," ...