美文网首页Swift编程刷题学编程Leetcode模拟面试
LeetCode 剑指 Offer 06. 从尾到头打印链表(s

LeetCode 剑指 Offer 06. 从尾到头打印链表(s

作者: freesan44 | 来源:发表于2021-08-09 17:52 被阅读0次

题目

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。


示例 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)")

相关文章

网友评论

    本文标题:LeetCode 剑指 Offer 06. 从尾到头打印链表(s

    本文链接:https://www.haomeiwen.com/subject/vdazvltx.html