码迷,mamicode.com
首页 > 其他好文 > 详细

<LeetCode OJ> 141. Linked List Cycle

时间:2016-01-13 07:08:50      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

141. Linked List Cycle

My Submissions
Total Accepted: 88665 Total Submissions: 241622 Difficulty: Medium

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

Follow up:
Can you solve it without using extra space?

Subscribe to see which companies asked this question

Hide Similar Problems
 (M) Linked List Cycle II


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 //思路首先:如果有环?遍历链表将无法走完,如果无环终会走到尾为NULL的位置
 //让一个指针每次走一个,一个指针每次走两个位置,如果其中一个为NULL则无环,如果相遇了
 //则有环
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL)
            return false;
        ListNode *showNode=head;
        ListNode *fastNode=head;
        while(true)
        {
            if(showNode->next!=NULL)
                showNode=showNode->next;
            else
                return false;
            if(fastNode->next!=NULL && fastNode->next->next!=NULL)    
                fastNode=fastNode->next->next;
            else
                return false;    
            if(showNode==fastNode)
                return true;
        }
        return false;
    }
};

注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50507131

原作者博客:http://blog.csdn.net/ebowtang


<LeetCode OJ> 141. Linked List Cycle

标签:

原文地址:http://blog.csdn.net/ebowtang/article/details/50507131

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!