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的更多相关文章
随机推荐
- PHPCMSV9 采集网址后,再采集内容,报错:“采集采集内容 没有找到网址列表,请先进行网址采集”
解决方法:直接清除v9_collection_history 表里的内容.
- C++ primer学习方法
C++ primer学习: 第一次可以跳着看.关键是要尽快用起来,在使用中熟练,而不是在细节中迷失. 以C++ Primer第五版为例,第一遍读的时候: Part1也就是前七章,除了6.6,6 ...
- 转 Jona Dany 一个20年架构师程序员的经验总结
1.估算问题解决所需要的时间,为自己定一个时间限制,1小时,30分钟,15分钟.如果这期间不能解决问题,那就去寻求帮助.不要做超级堆码员. 2.编程语言是一种语言,只是一种语言.只要理解一种语言的原理 ...
- css属性之appearance
appearance 属性允许您使元素看上去像标准的用户界面元素. 案例: 使 div 元素看上去像一个按钮 <!DOCTYPE html> <html> <head&g ...
- MSSQL 标准PROC 写法
MSSQL 标准PROC 写法 ALTER PROC [dbo].[usp_ADM_InsertFlowSortInfo]@FlowSortName NVARCHAR(50),AS/*PAGE: 分类 ...
- Android笔记(二):从savedIndstanceState发散
savedIndstanceState savedIndstanceState位于ActivityonCreate(Bundle savedInstanceState)方法的参数中.对这个参数的理解要 ...
- 关于springMVC框架访问web-inf下的jsp文件
问题:springMVC框架访问web-inf下的jsp文件,具体如下: 使用springMVC,一般都会使用springMVC的视图解析器,大概会这样配置 <property name=&qu ...
- hdu 5389 Zero Escape(记忆化搜索)
Problem Description Zero Escape, is a visual novel adventure video game directed by Kotaro Uchikoshi ...
- css+javascript 写的HTML5 微信端输入支付密码键盘
微信端没有纯数字键盘,用html5写了一个模仿ios输入支付密码键盘效果 keyboard.js var _keyboard = {}; $(document).ready(function(){ _ ...
- IIS7.0 Windows Server 2008 R2 下配置证书服务器和HTTPS方式访问网站
配置环境 Windows版本:Windows Server 2008 R2 Enterprise Service Pack 1 系统类型: 64 位操作系统 了解HTTPS 为什么需要 HTTPS ? ...