LintCode 102. Linked List Cycle

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

思路:
快慢指針

代碼:

class Solution {
public:
    /*
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    bool hasCycle(ListNode * head) {
        // write your code here
        if(head == NULL || head->next == NULL)
            return false;
            
        ListNode *fast = head;
        ListNode *slow = head;
        
        while(fast->next != NULL && fast->next->next != NULL){
            fast = fast->next->next;
            slow = slow->next;
            
            if(slow == fast)
                return true;
        }
        
        return false;
        
    }
};

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,129评论 0 23
  • 画中人说那年执着, 夕霞风月残留。 旧梦淡了新事, 一曲洗净蒙蒙烟雨。 旧泪微微湿了眼眸,细雨淡稀了想念。 风轻拂...
    角述阅读 267评论 0 1
  • 1,认真倾听,力争和客户同频共振 2,从客户的角度理解问题,解决问题,成交是顺便的事 3,从内心真诚的把客户当成朋...
    爱心语家庭教育薛辉阅读 191评论 0 0
  • 关键词:短婚史题主:女 问:冷大您好,听过两场您的亲面授课,感叹您腿真的长,也很让人亲近。书跟微问答都一直跟着看,...
    冷爱阅读 608评论 0 0