【leetcode刷题】T106-环形链表

时间:2022-06-26
本文章向大家介绍【leetcode刷题】T106-环形链表,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

【题目】

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。

示例 :
输入:head = [,,,-4], pos = 
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 :
输入:head = [,], pos = 
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 :
输入:head = [], pos = -1
输出:false
解释:链表中没有环。

进阶:

你能用 O(1)(即,常量)内存解决此问题吗?

【思路】

如果有两个指针first和second,first指针每次走一步,second指针每次走两步,那么当链表存在环时,first和second肯定会相遇,否则second指针先会指向链表末尾NULL。

【代码】

python版本

# 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
        """
        if not head:
            return False
        first = head
        second = head
        while True:
            if second.next and second.next.next:
                second = second.next.next
            else:
                return False
            first = first.next
            if first == second:
                return True

C++版本

/**
 * 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) {
        if(!head)
            return false;
        ListNode* first = head;
        ListNode* second = head;
        while(true){
            if(second->next && second->next->next)
                second = second->next->next;
            else
                return false;
            first = first->next;
            if(first == second)
                return true;
        }
    }
};