题目
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
解题思路
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func reverseList(_ head: ListNode?) -> ListNode? {
var frontNode = head
var backNode = head?.next
// 边界问题处理
if backNode == nil || frontNode == nil {
return frontNode
}
// 初始节点指向nil
frontNode?.next = nil
while backNode!.next != nil {
// 临时缓存下一个节点
let tempNode = backNode!.next
// 把backNode的指向反转
backNode?.next = frontNode
// 把指针移向反转后的节点
frontNode = backNode
// 把back指针移到下一个节点
backNode = tempNode
}
backNode!.next = frontNode
return backNode
}
}
let node2 = ListNode(2)
let node3 = ListNode(3)
let node4 = ListNode(4)
node2.next = node3
node3.next = node4
let res = Solution().reverseList(node2)
print("res:\(res?.val)\(res!.next!.val)\(res!.next!.next!.val)\(res!.next!.next!.next)")
网友评论