从尾到头打印链表
题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入: head = [1,3,2]
输出: [2,3,1]
链表节点创建函数:
function ListNode(val) {
this.val = val;
this.next = null;
}
解法:
// 解法1:借助数组逆序
var reversePrint = function(head) {
const res=[];
while(head){
res.push(head.val)
head=head.next
}
return res.reverse();
};
// 解法2:将链表倒置
// var reversePrint = function(head) {
// // 如果是空链表则退出 返回[]
// if(!head){
// return [];
// }
// // 获取倒置后的新链表
// let newHead=new ListNode(null);
// let currHead=new ListNode(head.val);
// head=head.next;
// while(head){
// newHead=currHead;
// currHead=new ListNode(head.val);
// currHead.next=newHead;
// head=head.next;
// }
// let res=[];
// // 遍历新链表
// while(currHead){
// res.push(currHead.val);
// currHead=currHead.next;
// }
// return res;
// };
// 解法3 --借助栈
var reversePrint = function(head) {
const res=[];
while(head){
res.unshift(head.val)
head=head.next
}
return res;
};
感悟:
个人感觉倒置链表是最好的方法 可能有点绕 但是只要绕着倒置的目的走 就能成功