JavaScript / TypeScript for LeetCode (107)

是差点运气,可我一直在努力!

当前进程:

  • 开始时间:2020.6.27
  • 结束时间:undefined

GitHub仓库:https://github.com/Cundefined/JavaScript-or-TypeScript-for-LeetCode

1、题目要求

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

2、解题思路

解题思路:
1、遍历一遍链表,记录其长度
2、以其长度,创建一个等长度的数组
3、从数组最后位置依次加入链表节点值

2.1、JavaScript Solution

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function (head) {
  if (head === null) {
    return [];
  }
  let len = 0;
  let curr = head;
  while (curr !== null) {
    len++;
    curr = curr.next;
  }

  const res = new Array(len);

  curr = head;

  let i = len - 1;

  while (curr !== null) {
    res[i--] = curr.val;
    curr = curr.next;
  }

  return res;
};

2.2、TypeScript Solution

/**
 * Definition for singly-linked list.
 * 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)
 *     }
 * }
 */

function reversePrint(head: ListNode | null): number[] {
  if (head === null) {
    return [];
  }
  let len: number = 0;
  let curr: ListNode | null = head;
  while (curr !== null) {
    len++;
    curr = curr.next;
  }

  const res: number[] = new Array(len);

  curr = head;

  let i: number = len - 1;

  while (curr !== null) {
    res[i--] = curr.val;
    curr = curr.next;
  }

  return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值