剑指offer中经典的算法题之从头到尾打印链表

话不多说上代码:

  我自己的算法是:

  

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

这是我没有参考其他人的答案自己想出来的简单的算法,算是比较糟糕了,思路是先反转链表,再进行打印

下面列出其他人比较经典的算法:

1. 利用栈,先进后出

2 . 递归

猜你喜欢

转载自www.cnblogs.com/lwmp/p/9692094.html