题目:通过有环链表,返回环路链表的开头结点.
核心代码:
<pre><code>` func findBeginingNode(headNode:ListNode) -> ListNode? {
var slow:ListNode? = headNode
var fast:ListNode? = headNode
// 环路节点相交
while fast != nil {
slow = slow?.next
fast = fast?.next?.next
if slow?.value == fast?.value {
break
}
}
// 校验
if fast == nil || fast?.next == nil {
return nil
}
// 重置开始节点
slow = headNode
while slow?.value != fast?.value {
slow = slow?.next
fast = fast?.next
}
return fast
}`</code></pre>
测试代码:
<pre><code>var circleHead:ListNode = ListNode(value: "1") var circelNode1:ListNode = ListNode(value: "2") var circelNode2:ListNode = ListNode(value: "3") var circelNode3:ListNode = ListNode(value: "4") circleHead.next = circelNode1 circelNode1.next = circelNode2 circelNode2.next = circelNode3 circelNode3.next = circleHead var beginingNode:ListNode? = listNodeManger.findBeginingNode(headNode: circelNode1) print("FlyElephant---环路链表开始值---\(beginingNode!.value!)")
</code></pre>