从尾到头打印链表
输入一个链表,从尾到头打印链表每一个节点的值。
思绪:先将链表每一个结点的值存入数组中,然后经由过程数组的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);
}
}