[剑指offer]从尾到头打印链表
思路:
创建静态全局变量arraylist,用递归找到最后一个元素,找到后依次加入arraylist。

递归实现:

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
public class Solution {
    ArrayList<Integer> arraylist=new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        if(listNode!=null){
            this.printListFromTailToHead(listNode.next);
            arraylist.add(listNode.val);
        }
        return arraylist;
    }
}

非递归实现:

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    ArrayList<Integer> arraylist=new ArrayList<Integer>();
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        Stack<Integer> stack=new Stack<Integer>();
        while(listNode!=null){
            stack.push(listNode.val);
            listNode=listNode.next;
        }
        ArrayList<Integer> list=new ArrayList<Integer>();
        while(!stack.isEmpty()){
            list.add(stack.pop());
        }
        return list;
    }
}

相关文章:

  • 2021-08-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
猜你喜欢
  • 2022-02-13
  • 2021-11-16
  • 2021-06-17
  • 2021-12-28
  • 2021-11-02
  • 2022-01-28
  • 2022-01-28
相关资源
相似解决方案