首页 > 其他 > 详细

LeetCode Solution-141

时间:2020-02-06 10:48:39      阅读:50      评论:0      收藏:0      [点我收藏+]
141. Linked List Cycle

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

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

技术分享图片

Example 2:

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

技术分享图片

Example 3:

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

技术分享图片

思路
解释一下所给输入中包含pos的意思,因为给的函数里面并没有这个输入。pos存在的意义是为了构造一个有环或无环的链表(从尾节点指向pos指向的节点,为-1则无环),而我们所给的就是头结点head,所以不能用pos来判断是否有环。
1.设置2个指针:fast和slow;
2.fast每次移动2个节点,slow每次移动一个节点;
3.如果fast和slow指向的节点相同,说明有循环,不相同则说明不存在循环。

Solution:

bool hasCycle(ListNode *head) {
    if (!head) return false;
    
    ListNode *fast = head, *slow = head;
    while (fast->next && fast->next->next) {
        fast = fast->next->next;
        slow = slow->next;
        if (fast == slow)   return true;
    }
    return false;
}

性能
Runtime: 12 ms??Memory Usage: 9.9 MB

LeetCode Solution-141

原文:https://www.cnblogs.com/dysjtu1995/p/12267649.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!