题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1: 输入:head = [1,3,2] 输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解题思路
/** * 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 * } * } */ public class ListNode { public var val: Int public var next: ListNode? public init(_ val: Int) { self.val = val self.next = nil } } class Solution { func reversePrint(_ head: ListNode?) -> [Int] { var tempList:[Int] = [] var node = head while (node != nil) { tempList.append(node!.val) node = node!.next } return tempList.reversed() } } let node2 = ListNode(2) let node3 = ListNode(3) let node4 = ListNode(4) node2.next = node3 node3.next = node4 let res = Solution().reversePrint(node2) print("res:\(res)")