从尾到头打印链表
输入一个链表,从尾到头打印链表每个节点的值。
思路:先将链表每个结点的值存入数组中,然后通过数组的reverse方法,即可从尾到头打印。
function ListNode(x){
this.val = x;
this.next = null;
}
function printListFromTailToHead(head){
if(!head) {
return 0;
}
else {
let arr = new Array();
let cur = head;
while(cur) {
arr.push(cur.val);
cur = cur.next;
}
return arr.reverse();
}
}
let node1 = new ListNode(1);
let node2 = new ListNode(2);
let node3 = new ListNode(3);
node1.next = node2;
node2.next = node3;
console.log(printListFromTailToHead(node1));
这里需要反向打印链表,于是很自然的可以想到用递归来实现。要实现反过来输出链表,我们每次访问到一个节点的时候,先递归输出它后面的节点,再输出该节点自身,这样链表的输出结果就反过来了。
function printListFromTailToHead(head) {
if(head !== null) {
printListFromTailToHead(head.next);
console.log(head.val);
}
}