剑指offer_03:从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:
输入:head = [1,3,2]
输出:[2,3,1]

限制:
0 <= 链表长度 <= 10000

1、两次遍历,第一次获取链表长度,建立数组,第二次反向存数组

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        int size=0;
        ListNode node=head;
        while(node!=null){
            node=node.next;
            size++;
        }
        int[] res=new int[size];
        node=head;
        size--;
        while(node!=null){
            res[size--]=node.val;
            node=node.next;
        }
        return res;
    }
}

2、递归

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> list=new ArrayList<Integer>();
    public int[] reversePrint(ListNode head) {
        
        re(head);
        int[] res=new int[list.size()];
        for(int i=0;i<list.size();i++){
            res[i]=list.get(i);
        }
        return res;
    }
    public void re(ListNode node){
        if(node==null){
            return;
        }
        re(node.next);
        list.add(node.val);
    }
}

3、栈

/**
 * 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> stack =new Stack<>();
        ListNode node=head;
        while(node!=null){
            stack.push(node.val);
            node=node.next;
        }
        int[] res=new int[stack.size()];
        for(int i=0;i<res.length;i++){
            res[i]=stack.pop();
        }
        return res;
    }
}
posted @ 2020-11-09 21:39  小昊子丫  阅读(60)  评论(0编辑  收藏  举报