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

141 Linked List Cycle 环形链表

时间:2018-04-06 00:13:45      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:des   com   class   nod   lin   null   false   gpo   fast   

给定一个链表,判断链表中否有环。
补充:
你是否可以不用额外空间解决此题?
详见:https://leetcode.com/problems/linked-list-cycle/description/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==nullptr)
        {
            return false;
        }
        ListNode *slow=head;
        ListNode *fast=head;
        while(fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)
            {
                return true;
            }
        }
        return false;
    }
};

 

141 Linked List Cycle 环形链表

标签:des   com   class   nod   lin   null   false   gpo   fast   

原文地址:https://www.cnblogs.com/xidian2014/p/8724877.html

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