美文网首页
leetcode:逆序链表

leetcode:逆序链表

作者: grace_fang | 来源:发表于2019-12-09 21:21 被阅读0次

    在工作中意识到算法能力还是很差,所以捡起来重新刷题。
    与君共勉之。

    package com.wuli.algorithm.逆序链表;
    
    import java.util.ArrayList;
    import java.util.Stack;
    
    /**
     * @author jincheng.fjc
     * @date 2019/12/02
     */
    public class Solution {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
    
        /**
         * 利用栈的特点
         *
         * @param listNode
         * @return
         */
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            Stack<Integer> stack = new Stack<>();
            while (listNode != null) {
                stack.push(listNode.val);
                listNode = listNode.next;
            }
    
            ArrayList<Integer> list = new ArrayList<>();
            while (!stack.isEmpty()) {
                list.add(stack.pop());
            }
            return list;
        }
    
        /**
         * 超级简洁递归版本
         */
        public ArrayList<Integer> printListFrom(ListNode listNode) {
            if (listNode != null) {
                this.printListFrom(listNode.next);
                arrayList.add(listNode.val);
            }
            return arrayList;
        }
    
        public static void main(String[] args) {
            ListNode listNode1 = new ListNode(1);
            ListNode listNode2 = new ListNode(2);
            ListNode listNode3 = new ListNode(3);
            listNode1.next = listNode2;
            listNode2.next = listNode3;
    
            ArrayList<Integer> arrayList2 = new ArrayList<Integer>();
            Solution solution = new Solution();
            arrayList2 = solution.printListFromTailToHead(listNode1);
            System.out.println(arrayList2);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:leetcode:逆序链表

          本文链接:https://www.haomeiwen.com/subject/kgbigctx.html