一、从尾到头打印链表
1、非递归
function printListFromTailToHead(head)
{
// write code here
let arr = []
while(head){
arr.unshift(head.val)
head = head.next
}
return arr
}
2、递归
function printListFromTailToHead(head)
{
// write code here
let arr = [];
function cur(head){
if(head){
cur(head.next);
arr.push(head.val)
}
};
cur(head);
return arr;
}
二、反转链表
1、双指针
var reverseList = function(head) {
if(!head || !head.next) return head
let pre = null, cur = head
while(cur){
let temp = cur.next
cur.next = pre
pre = cur
cur = temp
}
return pre
};
2、栈
function ListNode(val) {
this.val = val;
this.next = null;
}
var reverseList = function(head) {
if(!head || head.next == null) return head
let arr = [];
while(head){
arr.push(head.val);
head = head.next
}
let node = new ListNode(arr.pop())
let cur = node
while(arr.length){
let temp = new ListNode(arr.pop())
node.next = temp
node = node.next
}
node.next = null
return cur
};
3、递归
var reverseList = function(head) {
if(!head || !head.next) return head
let node = reverseList(head.next);
head.next.next = head;
head.next = null;
return node;
};