(LeetCode OJ) 141. Linked List Cycle

页面导航:首页 > 软件编程 > C 语言 > (LeetCode OJ) 141. Linked List Cycle

(LeetCode OJ) 141. Linked List Cycle

来源: 作者: 时间:2016-01-15 14:31 【

141 Linked List CycleMy SubmissionsQuestionTotal Accepted: 88665 Total Submissions: 241622 Difficulty: MediumGiven a linked list, determine if it has a cycle

141. Linked List Cycle



Question

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?

 to see which companies asked this question

Hide Tags
 Two
Pointers

Hide Similar Problems


 

/**
 * 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;
    }
};
Tags:

相关文章

    文章评论

    最 近 更 新
    热 点 排 行
    Js与CSS工具
    代码转换工具
    
    <