leetcode 之 Linked List Cycle
来源:互联网 发布:谷歌seo插件 编辑:程序博客网 时间:2024/05/22 13:21
原题:Given a linked list, determine if it has a cycle in it.
这么高端大气的题目方法比较特殊,当然学渣也是问了学长才知道的,弄俩指针,一个走的快,一个走的慢,要是有环就会相遇(这个关于相遇的问题,一个走一步,另一个走2步肯定会相遇,要是一个走2步,另一个走4步,那就有可能不相遇了。。。不过还是走平常路吧),没环走的快的就会走到NULL。代码如下:
class Solution {public: bool hasCycle(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode * first = head; //每次前进2步 ListNode * second = head; //每次前进1步 //first = head; //second = head; if(first == NULL){ //list为空,则无 return false; } if(first->next == NULL){ //list 只有一个元素,无环 return false; } first = first->next; while(first->next != NULL && first->val != second->val){ //当到链的末尾或者两者相遇时中断 second = second->next; if(first->next->next==NULL){ //如果有环,first再快也不会有空,只要其有空就说明无环 return false; } first = first->next->next; } if(first->next == NULL){ return false; } else{ return true; } }};
- leetcode 之 Linked List Cycle
- LeetCode之Linked List Cycle
- LeetCode之Linked List Cycle
- leetcode之Linked List Cycle
- leetcode之Linked List Cycle
- leetcode之Linked List Cycle
- LeetCode之Linked List Cycle
- 【LeetCode】之Linked List Cycle
- leetcode之Linked List Cycle
- LeetCode 之 Linked List Cycle
- leetcode之linked List cycle && linked List cycle II
- leetcode Linked List Cycle & Linked List Cycle ||
- LeetCode之Linked List Cycle II
- LeetCode之Linked List Cycle II
- leetcode之Linked List Cycle II
- leetcode之Linked List Cycle II
- LeetCode之Linked List Cycle II
- leetcode之Linked List Cycle II
- Android应用启动时屏幕黑屏或白屏解决方案
- Red and Black
- 对丰田暴冲事故的软件调查报告——嵌入式软件工程师必看
- web.xml各个配置的加载顺序
- PHP 一些琐碎
- leetcode 之 Linked List Cycle
- c语言演示static和auto类型的区别的整型数转字符串函数
- 关于chromium中几个类的类图:class-diagram-webkit-webcore-to-chrome-browser
- GIT和SVN之间的五个基本区别
- 长篇大论和实际操作
- 算法入门2:分治算法(上)
- PB5.0开发流驱动框架的流程(图文)
- java中的排序问题
- java replaceAll(,)方法的使用 多个逗号变一个