首页 > 其他 > 详细

Linked List Cycle

时间:2015-04-17 17:58:58      阅读:240      评论:0      收藏:0      [点我收藏+]

Given a linked list, determine if it has a cycle in it.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if(!head)
13             return false;
14         ListNode* fast = head->next;
15         ListNode* slow = head;
16         while(fast) {
17             if(fast == slow)
18                 return true;
19             if(fast->next&&fast->next->next){//短路的技巧
20                 fast = fast->next->next;
21                 slow = slow->next;
22             }
23             else
24                 return false;
25         }
26         return false;
27     }
28 };

  设置两个指针,一个快指针,一个慢指针。快指针每次走两步,慢指针每次走一步,如果相遇就是有环。

  19行先判断快指针能不能走1步,如果能在判断2步之后是不是链表末尾,如果不是末尾就可以向下走。

==============================我是分割线=============================================

  《编程之美》上看到一道题目,判断两个两个链表(无环)是否相交,可以转化为这题的解法,把第二个链表头接到另一个的末尾,在检测是否有环,有环就是相交。

  两一种解法更简单,比较倒数第二节链表是否相等越来愈感受到算法的美妙了.QAQ

Linked List Cycle

原文:http://www.cnblogs.com/ittinybird/p/4435210.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!