【剑指offer】6从尾到头打印链表

题目描述

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

输入: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 {
    public int[] reversePrint(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        while(head != null){
             stack.push(head);
             head = head.next;
         }
        int[] res =  new int[stack.size()];
        int i = 0;
        while(!stack.isEmpty() && i < res.length){
            ListNode node = stack.pop();
            res[i] = node.val;
            i++;
        }
        return res;
    }
}

2.递归实现

class Solution {
    ArrayList<Integer> res = new ArrayList<>();
    public int[] reversePrint(ListNode head) {
        recur(head);
        int[] print = new int[res.size()];
        for(int i = 0; i < res.size(); i++){
          print[i] = res.get(i);
      }
      return print;
    }
    private void recur(ListNode node){
        if(node != null){
           if(node.next != null){
               reversePrint(node.next);
           }
           res.add(node.val);
       }
    } 
}
发布了89 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Dawn510/article/details/105086519