题目:如果链表的节点数量是奇数返回中间节点,如果是偶数返回两个中间节点的任意一个.
代码:
// 链表的中点
func findCenterNode(head:ListNode?) -> ListNode? {
if head == nil || head?.next == nil {
return head
}
var startNode:ListNode? = head
var nextNode:ListNode? = head?.next
while nextNode != nil {
startNode = startNode?.next
nextNode = nextNode?.next?.next
}
return startNode
}
测试:
var centerNode:ListNode? = searchNode.findCenterNode(head: searchHeadNode)
if centerNode != nil {
print("FlyElephant-中点的Value--\(centerNode!.value!)")
} else {
print("中点没有值")
}