- Notifications
You must be signed in to change notification settings - Fork24
Open
Labels
Description
递归
- “递” 阶段先走至链表末尾
head === null
为递归终止条件- “归” 阶段依次将每个节点上的值加入列表,即可实现链表值的倒序输出
constreversePrint=function(head){returnhead===null ?[] :reversePrint(head.next).concat(head.val)}
- 时间复杂度: O(n)
- 空间复杂度: O(n)
栈
- 借助两个栈,先将链表中每个节点的值 push 进 stack1
- 然后再从 stack1 中 pop 出每个节点的值放入 stack2
constreversePrint=function(head){conststack1=[]conststack2=[]while(head){stack1.push(head.val)head=head.next}constk=stack1.length;for(leti=0;i<k;i++){stack2[i]=stack1.pop()}returnstack2}
- 时间复杂度: O(n)
- 空间复杂度: O(n)