输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
答案:头插法
1
function ListNode(val) {this.val = val;this.next = null;}const head = new ListNode()const head1 = new ListNode()const head2 = new ListNode()const head3 = new ListNode()Object.assign(head,{val:undefined,next:head1})Object.assign(head1,{val:1,next:head2})Object.assign(head2,{val:2,next:head3})Object.assign(head3,{val:3,next:null})var reversePrint = function(head) {const res = []function recur (ListNode){if(ListNode.next===null) {res.push(ListNode.val)return}recur(ListNode.next)if(ListNode.val)res.push(ListNode.val)}recur(head)return res}reversePrint(head)
2
var reversePrint = function (head) {
if (head === null) return []
const res = []
while (head) {
res.push(head.val)
head = head.next
}
return res.reverse()
}
3
var reversePrint = function(head) {
if (head === null) return []
const res=[]
while(head){
res.unshift(head.val)
head=head.next
}
return res
}
4
// 首先将链表反转
function reverseLink(head) {
if (head === null || head.next === null) return head
let p = head.next
head.next = null
let tmp = null
while (p !== null) {
tmp = p.next // tmp 指针前进(保存下一个指针信息)
p.next = head // 指针反转
head = p // head 指针前进
p = tmp // p 指针前进
}
return head
}
//再顺序输出链表
