剑指offer:003从尾到头打印链表 附:java实现

题目描述

从尾到头打印链表

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

思路: 核心算法

    while(listNode!=null) {   //倒置链表 头节点变成pre
            next = listNode.next;
            listNode.next = pre;
            pre = listNode;
            listNode = next;
        }

java实现


import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list=new ArrayList<Integer>();
        ListNode pre=null;
        ListNode next=null;

        while(listNode!=null){   //倒置链表 头节点变成pre
            next=listNode.next;
            listNode.next=pre;
            pre=listNode;
            listNode=next;
        }
        while(pre!=null){
            list.add(pre.val);
            pre=pre.next;
        }
        return list;
    }
}
发布了69 篇原创文章 · 获赞 5 · 访问量 2185

猜你喜欢

转载自blog.csdn.net/qq_42139889/article/details/104338391