从尾到头打印链表

题目描述:
从尾到头打印链表。

方法一:使用辅助栈

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
         
        if(listNode == null)
            return new ArrayList<Integer>();
         
        //使用辅助栈
        Stack<Integer> stack = new Stack<>();
        ListNode p = listNode;
         
        while(p != null) {
            stack.push(p.val);
            p = p.next;
        }
         
        ArrayList<Integer> result = new ArrayList<>();
        while(!stack.isEmpty()) {
            result.add(stack.pop());
        }
         
        return result;
    }
     
}

方法二:采用递归

/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.*;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
         
        if(listNode == null) {
            return new ArrayList<Integer>();
        }
         
        ArrayList<Integer> result = new ArrayList<>();
         
        //递归
        corePrint(listNode, result);
         
        return result;
    }
     
     
    //递归函数
    public void corePrint(ListNode node, ArrayList<Integer> result) {
         
        if(node == null) {
            return;
        }
         
        corePrint(node.next, result);
        result.add(node.val);
    }
     
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容