题解 | #从尾到头打印链表#

从尾到头打印链表

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035

/*class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * @param head ListNode类
 * @return int整型一维数组
 */
export function printListFromTailToHead(head: ListNode): number[] {
    // write code here
      if (!head) {
        return []
    }
    let tempHead: ListNode | null = head
    const arr = []
    do {
        arr.unshift(tempHead.val)
        tempHead = tempHead.next
    } while (tempHead)
    return arr
}

解题思路: 创建一个数组,遍历链表不断往数据前插入数据

全部评论

相关推荐

千千倩倩:简历问题有点多,加v细聊
点赞 评论 收藏
分享
09-13 08:41
服装/纺织设计
那一天的Java_J...:你第一次参加面试吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务