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的更多相关文章
随机推荐
- python查看模块及相关函数帮助
Question: 如何查看正则表达式模块re及其相关函数的意义 1.终端命令行下 python >> import re >> help(re) Help on module ...
- C++学习笔记1——const
Const 限定符 1. 等价 //const对象必须初始化//C++中const修饰的变量不能改变//C中const修饰的变量可以通过指针修改 2. ; const int j = i;//变量给常 ...
- C++服务器linux开发环境管理
在游戏服务器开发中,跨平台不是必须的.线上游戏既有windows下的C++..Net服务器也有linux下的C++.go.erlang服务器.但是无论如何都要保证开发环境和线上运行环境的一致,否则不同 ...
- Swift—使用try?和try!区别-备
在使用try进行错误处理的时候,经常会看到try后面跟有问号(?)或感叹号(!),他们有什么区别呢? 1.使用try? try?会将错误转换为可选值,当调用try?+函数或方法语句时候,如果函数或方 ...
- (摘自ItPub)物理standby中switchover时switchover pending的解决办法
http://www.itpub.net/thread-1782245-1-1.html DataGuard一主一物理备,sid为primary和standby,现在要把primary切换成备库,st ...
- 51单片机 Keil C 延时程序的简单(晶振12MHz,一个机器周期1us.)
一. 500ms延时子程序 void delay500ms(void) { unsigned char i,j,k; ;i>;i--) ;j>;j--) ;k>;k--); } 产生 ...
- Xamarin.Forms App Settings
配合James Montemagno的Component [Settings Plugin],实现Xamarin.Forms的设置. 更新系统配置且不需要进行重启app. 方式一xml Xamarin ...
- ExpandableListView(可展开的列表组件)的说明以及其用法
ExpandableListView的用法和ListView非常像,只是其所显示的列表项应该由ExpandableListAdapter提供,下面是它的xml属性及说明: 然而,接下来是用事实说话了: ...
- iOS越狱开发手记 - iOS9.3 dyld_decache不能提取arm64的dyld的解决方法
参考以下文章 http://iosre.com/t/when-dyld-decache-fails-on-dyld-shared-cache-arm64-dsc-extractor-saves-our ...
- HDU_2056——相交矩形的面积
Problem Description Given two rectangles and the coordinates of two points on the diagonals of each ...