首页 > 其他 > 详细

leetcode141:

时间:2020-08-16 10:28:56      阅读:67      评论:0      收藏:0      [点我收藏+]

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

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

示例 1:

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

 

哈希表

=============================================Python=========================================

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        s = set()
        if not head:
            return False
        while head:
            if head not in s:
                s.add(head)
                head = head.next
            else:
                return True
        return False

=========================================Java=======================================

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        HashSet<ListNode> s = new HashSet<>();
        if (head == null) {
            return false;
        }
        while (head != null) {
            if (s.contains(head) == false) {
                s.add(head);
                head = head.next;
            } else {
                return true;
            }
        }
        return false;
    }
}

=========================================Go==================================

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func hasCycle(head *ListNode) bool {
    m := make(map[*ListNode]int)
    for head != nil {
        if _, ok := m[head]; ok{
            return true
        }
        m[head] = 1
        head = head.Next
    }
    return false
}

 

双指针

=============================================Python=========================================

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        fast = slow = head
        if not head:
            return False
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if slow == fast:
                return True
        return False

 

leetcode141:

原文:https://www.cnblogs.com/liushoudong/p/13496845.html

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