142. 环形链表 II golang
生活随笔
收集整理的這篇文章主要介紹了
142. 环形链表 II golang
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
142. 環(huán)形鏈表 II
給定一個(gè)鏈表,返回鏈表開(kāi)始入環(huán)的第一個(gè)節(jié)點(diǎn)。 如果鏈表無(wú)環(huán),則返回 null。
為了表示給定鏈表中的環(huán),我們使用整數(shù) pos 來(lái)表示鏈表尾連接到鏈表中的位置(索引從 0 開(kāi)始)。 如果 pos 是 -1,則在該鏈表中沒(méi)有環(huán)。
說(shuō)明:不允許修改給定的鏈表。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:tail connects to node index 1
解釋:鏈表中有一個(gè)環(huán),其尾部連接到第二個(gè)節(jié)點(diǎn)。
code
/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/ func detectCycle(head *ListNode) *ListNode {res := hasCycle(head) if res == nil {return nil}for head != res {head = head.Nextres = res.Next}return res }func hasCycle(head *ListNode) *ListNode {if head == nil {return nil}firstNode, secondNode := head, head for secondNode != nil && secondNode.Next != nil {firstNode = firstNode.NextsecondNode = secondNode.Next.Nextif firstNode == secondNode {return secondNode}}return nil }總結(jié)
以上是生活随笔為你收集整理的142. 环形链表 II golang的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: DNF第三季远古2流程?说明出什么然后再
- 下一篇: 206. 反转链表 golang