leetcode---C++实现---141. Linked List Cycle(环形链表)

题目

level:easy

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.

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle

解题思路

想象有两个指针,一个指针每次只往后移动一个节点,另一个指针每次往后移动两个节点,若节点能形成环,则这两个指针在移动过程中必定会重合;

  1. 声明两个指针,一个指针每次移动一个节点,另一个指针每次移动两个节点;
  2. 当遇到NULL时,必定不成环;若遍历过程中两节点相遇,则必定成环。

算法实现(C++)

/**
 1. Definition for singly-linked list.
 2. struct ListNode {
 3.     int val;
 4.     ListNode *next;
 5.     ListNode(int x) : val(x), next(NULL) {}
 6. };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head)
            return false;
        ListNode* oneNode = head;//该指针每次只往后移动一个节点
        ListNode* twoNode = head->next;//该指针每次往后移动两个节点
        while (oneNode && twoNode && twoNode->next)
        {
            if (oneNode == twoNode)
                return true;
            oneNode = oneNode->next;
            twoNode = twoNode->next->next;
        }
        //程序运行至此,则说明退出了while循环,说明上述节点有NULL存在,则必定不成环
        return false;
    }
};
复杂度分析
  1. 时间复杂度:O(n),当链表不成环时,节点遍历到NULL则结束;当链表成环时,则在成环节点的有限圈数内两指针必定相遇;
  2. 空间复杂度:O(1),只需有限的两个指针即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值