141. Linked List Cycle

题目:

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:

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:

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:

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, 10^4].
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index in the linked-list.

 

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

 

 

 

思路1:

判断是否为环型列表,最最直白的思路0是用一个哈希表,单指针遍历,把遇到过的都记下来,如果遇到相同的就返回true,如果一直遍历到NULL,就返回false。这个就不写了,这里讨论follow up中O(1)空间复杂度的两种方法。思路1先讲标准解法双指针。首先如果head为空那白搭,直接返回false。之后用一快一慢双指针来遍历,在循环中满指针每次走一步,快指针每次走两步,如果走到NULL就说明没有环,如果走着走着发现快慢指针相等了,那必是环,返回true即可。

 

 

 


 

代码1:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head)
            return false;
        ListNode *p = head, *q=head;
        while(q->next&&q->next->next)
        {
            p=p->next;
            q=q->next->next;
            if(p==q)
                return true;
        }
        return false;
    }
};

 

 

 

思路2:

这个思路和思路0相反,我们不能记录每个点,我们就把遍历的每个点改成同一个不会出现的值,如果遍历的时候发现了这个值,那就说明有环。这个思路有局限性:首先出现的这个值是不存在val范围内的,但是因为这题val范围给了,因此可以解决,范围给的是10^5,我们直接选一个1e6,然后开始单指针遍历,每次比较,如果当前值是1e6则直接返回,否则把当前值改成1e6,直到遍历到NULL。这题如果val范围给的是[INT_MIN, INT_MAX],这种方法就不行了,还是要用标准的双指针,而且这题再往下的follow up通常是找那个入环的点,用双指针也是更方便的。

 

 

 

 

代码2:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        int test=1e6;
        while(head)
        {
            if(head->val==test)
                return true;
            head->val=test;
            head=head->next;
        }
        return false;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值