LeetCode算法题141:环形链表解析

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

进阶:
你能否不使用额外空间解决此题?

这个题如果是常规思路的话就是选择一个容器来存储所有遍历过的链表节点,然后检测下一个是否已经存在在容器中,考虑到需要使用有find方法的容器,这里就使用set来存储。C++代码就是这样的思路,然后python代码使用了另外的思路,这个思路的空间复杂度更低,时间复杂度会提高一些,这个思路就是设置两个指针来遍历链表,一快一慢,如果有环,那么总会有快的追上慢的(被套圈),否则快的遍历到了空指针,则一定没有环。
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) {
        set<ListNode *> nodes;
        ListNode *p = head;
        while(p!=NULL){
            if(nodes.find(p)!=nodes.end()) return true;
            else{
                nodes.insert(p);
                p = p->next;
            }
        }
        return false;
    }
};

python3源代码:

# 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 head==None or head.next==None:
            return False
        pSlow = head
        pFast = head.next
        while pFast!=None and pFast.next!=None:
            if pSlow==pFast:
                return True
            pSlow = pSlow.next
            pFast = pFast.next.next
        return False

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/83831286