剑指 Offer 06. 从尾到头打印链表
剑指 Offer 06. 从尾到头打印链表
题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入:head = [1,3,2]
输出:[2,3,1]
题解:
1.递归
- 记录深度,递归到链表尾部;
- 将深度化为数组长度,将回溯结果正序放入数组当中。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
int res [];
int i =0;
int j= 0;
public int[] reversePrint(ListNode head) {
solve(head);
return res;
}
public void solve(ListNode head){
if(head==null){
res = new int[i];
return;
}
i++;
solve(head.next);
res[j++] = head.val;
}
}
2.使用栈实现,利用栈的特性(先进后出),把链表从头到尾遍历添加到栈里面,再一一出栈添加到数组里。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> i = new Stack<Integer>();
while(head!=null){
i.push(head.val);
head=head.next;
}
int [] res = new int[i.size()];
for(int s =0;s<res.length;s++)
{
res[s] = i.pop();
}
return res;
}
}