题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点.
核心代码:
func reverseNodeList(head:ListNode?) -> ListNode? {
if head == nil || head?.next == nil {
return head
}
var headNode:ListNode? = head
var reverseHeadNode:ListNode?
var preNode:ListNode?
while headNode != nil {
let tempNode = headNode?.next // 保留继续循环的节点
if tempNode == nil {
reverseHeadNode = headNode // 最终返回的节点
}
headNode?.next = preNode
preNode = headNode
headNode = tempNode
}
return reverseHeadNode
}
测试代码:
var searchNode:SearchNode = SearchNode()
var reverseNode:ListNode? = searchNode.reverseNodeList(head: searchHeadNode)
searchNode.printList(reverseNode)