LeetCode -- Linked List Cycle AC Code C 语言

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

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

image

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

image

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

image

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

要是看了前面的引言部分,有了思路这个判断链表中是否有环的问题就比较简单了,之前想的是判断链表中是否有环可以通过首尾指针一起后退的方法,直至相遇,但是没有考虑单向链表的情况。所以这种思路某种情况是不可行的。

官方介绍的判断链表中是否存在环的方法是使用快慢指针,让两个前进速度不同的指针分别去遍历整个链表,当链表中存在环时,那么前进速度快的那个指针就会因素前速速度快的缘故在某个时间点与慢指针重合。反过来,当快慢指针相同时,也就说明链表中存在环。这样就能方便的进行判别了。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode ListNode;
bool hasCycle(struct ListNode *head) {
    ListNode *runner1, *runner2;
    runner1 = runner2 = head;
    
    while( runner1 != NULL){
        
        if( runner1->next != NULL && runner1->next->next != NULL){
            runner1 = runner1->next->next;
        }else{
            return false;
        }
        runner2 = runner2->next;
        
        if( runner1 == runner2) return true;
    }
    
    return false;
  
}

你可能感兴趣的:(LeetCode -- Linked List Cycle AC Code C 语言)