[Leetcode141]环形链表

给定一个链表,判断链表中是否有环。

这道题很巧妙,可以用两个指针去做,一个指针步长为1,另一个步长为2,如果有环的话,就变成了追击问题,迟早相遇。如果没环就会最终指向NULL。因为大的步长为2,所以先把链表为空或者为一个结点且无环的情况排除。

python:

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

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None:
            return False
        if head.next == None:
            return False
        slow = head
        fast = head
        while fast:
            slow = slow.next
            if fast.next :
                fast = fast.next.next
                if slow == fast:
                    return True
            else:
                return False
        return False

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) {
        if(head == NULL) return false;
        if(head->next == NULL) return false;
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast){
            slow = slow->next;
            if(fast->next){
                fast = fast->next->next;
                if(fast == slow) return true;
            }
            else return false;
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/83047222