linked_list_cycle

2022-12-14 浏览 (682)

linked_list_cycle.go 源码

package main

//环形链表

//使用set判重
func hasCycle1(head *ListNode) bool {
	set := map[*ListNode]bool{}
	for head != nil {
		if _, ok := set[head]; ok {
			return true
		}
		set[head] = true
		head = head.Next
	}
	return false
}

//快慢指针法
func hasCycle2(head *ListNode) bool {
	slow, fast := head, head
	for fast != nil && fast.Next != nil {
		slow, fast = slow.Next, fast.Next.Next
		if slow == fast {
			return true
		}
	}
	return false
}

你可能感兴趣的文章

add_two_numbers

add_two_numbers_ii

intersection_linked_lists

  • 所属分类: 后端技术
  • 本文标签: 技术
  • 版权声明: 本文链接 https://seaxiang.com/blog/190a029d878248a2bc3a096d617a2169