前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 剑指 Offer 06. 从尾到头打印链表(swift)

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

原创
作者头像
freesan44
修改2021-08-18 14:25:18
3900
修改2021-08-18 14:25:18
举报
文章被收录于专栏:freesan44freesan44

题目

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

 `

示例 1:

输入:head = 1,3,2

输出:2,3,1

 `

限制:

0 <= 链表长度 <= 10000

解题思路

代码语言:txt
复制
/**
 * 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)")

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档