剑指offer(3)从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

题目分析

比较简单,主要注意下从尾到头,可以用栈可以用递归,我给出我比较喜欢的代码吧

代码

/* function ListNode(x){
 this.val = x;
 this.next = null;
 }*/
function printListFromTailToHead(head) {
  // write code here
  const res = [];
  let pNode = head;
  while (pNode !== null) {
    res.unshift(pNode.val);
    pNode = pNode.next;
  }
  return res;
}

 

posted @ 2017-10-17 18:27  汕大小吴  阅读(2009)  评论(0编辑  收藏  举报