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

【LeetCode】Linked List Cycle

时间:2014-11-26 01:31:06      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:leetcode

    题意:

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

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


     思路:

     如何判断一个链表存在环?可以设置两个指针,一个快,一个慢,沿着链表走,在无环的情况下,快指针很快到达终点。如果存在环,那么,快指针就会陷入绕圈,而最后被慢指针追上。


     代码:

     C++:

/**
 * 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) {
        /*初始都指向 head */
        ListNode *pfast = head,*pslow = head;
        do{
            /*快指针两倍速*/
            if(pfast != NULL) pfast = pfast->next;
            if(pfast != NULL) pfast = pfast->next;

            /*到达 null,无环 */
            if(pfast == NULL) return false;

            /*慢指针*/
            pslow = pslow->next;
        }while(pfast != pslow);
        return true;
    }
};

     Python:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @return a boolean
    def hasCycle(self, head):
        
        pfast = head
        pslow = head
        
        while True:
            if pfast != None:
                pfast = pfast.next
            if pfast != None:
                pfast = pfast.next
            
            if pfast == None:
                return False
            
            pslow = pslow.next
            
            if pfast == pslow:
                break
        
        return True
        


【LeetCode】Linked List Cycle

标签:leetcode

原文地址:http://blog.csdn.net/jcjc918/article/details/40432831

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