从尾到头打印链表

//思路一:
//先反转链表,在从头到尾打印

//从尾到头打印链表
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> res = new ArrayList<>();

    //逆置该链表
    ListNode head = reverse(listNode);
    while(head!=null){
        res.add(head.val);
        head = head.next;
    }
    return res;
}

private ListNode reverse(ListNode listNode){
    ListNode pre = null;
    ListNode cur = listNode;
    while(cur!=null){
        ListNode next = cur.next;
        cur.next = pre;

        pre = cur;
        cur = next;
    }
    return pre;
}
//思路二:
//递归思路
//要逆序打印链表 1->2->3(3,2,1),可以先逆序打印链表 2->3(3,2),最后再打印第一个节点 1。
//链表 2->3 可以看成一个新的链表,要逆序打印该链表可以继续使用求解函数。

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
    ArrayList<Integer> res = new ArrayList<>();
    if (listNode == null){
        return res;
    }
    if(listNode.next==null){
        res.add(listNode.val);
        return res;
    }
    ArrayList<Integer> next = printListFromTailToHead(listNode.next);
    res.addAll(next);
    res.add(listNode.val);
    return res;
}

https://www.mianshi.onlinehttps://www.i9code.cn

本文由博客一文多发平台 OpenWrite 发布!

逃跑的眼镜_bvbEK5
7 声望0 粉丝