解法1:
使用栈,遍历一遍链表,将链表中的元素入栈,然后就链表中的元素依次加入返回数组中,即达到逆序的效果
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> st=new LinkedList<>();
ListNode cur=head;
while(cur!=null){
st.push(cur.val);
cur=cur.next;
}
int[] ans=new int[st.size()];
for(int i=0;i<ans.length;i++){
ans[i]=st.pop();
}
return ans;
}
}
//O(n)
//O(n)
解法2:
反转链表,将链表反转后,从新的头节点往后遍历得到一个逆序序列
class Solution {
public int[] reversePrint(ListNode head) {
ListNode pre=null,cur=head,next;
int num=0;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
num++;//统计链表中的节点的数量
}
cur=pre;//指向反转后的新的头节点
int[] ans=new int[num];
int i=0;
while(cur!=null){
ans[i++]=cur.val;
cur=cur.next;
}
return ans;
}
}
//O(n)
//O(1)
解法3:
递归法,递归的本质就是一个栈,因此递归做法和解法一辅助栈做法本质上一样
class Solution {
ArrayList<Integer> tmp=new ArrayList<>();
public int[] reversePrint(ListNode head) {
dfs(head);
int[] ans=new int[tmp.size()];
for(int i=0;i<ans.length;i++){
ans[i]=tmp.get(i);
}
return ans;
}
public void dfs(ListNode head){
if(head==null){
return;
}
dfs(head.next);
tmp.add(head.val);
}
}
//O(n)
//O(n)