linked list 5

1. Question: Given a linked list, determine whether it is a circular linked list

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

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


2. Answer: The problem is that the linked list is a singly linked list with only one pointer, so the loop must be at the end of the list, and there is no node behind the loop. Therefore, the solution is to let one node take 2 steps at a time, and the other node take one step. If it is a circular linked list, there must be times when they meet.


3. C++ code

/**
 * 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) {
        ListNode *curr = head;
        ListNode *currTwoStep = head;
        
        if(!curr|| !curr->next)
            return false;
        
        currTwoStep = curr->next;
        
        while(curr && currTwoStep){
            if(curr == currTwoStep) //Fast node, encountered a slow node
                return true;
            
            if(!currTwoStep->next)
                return false;
            
            currTwoStep = currTwoStep->next->next; //The fast node takes 2 steps, and the slow node takes 1 step
            curr = curr->next;
        }
        return false;
    }
};

python code

# 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
        """
        
        slow,fast = head,head
        while fast and fast.next:
            slow,fast = slow.next,fast.next.next
            if slow is fast:
                return True
        return False
        

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325635928&siteId=291194637