10、从尾到头打印链表

版权声明:版权所有 https://blog.csdn.net/qq_42253147/article/details/86435239

题目

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

思路

  • 剑指offer的思路,递归的思路,只要链表不为空,一直往后进行遍历,然后直到到达链表的末尾,就开始用数组保存下来结果

代码


 将链表反转,然后依次打印信息进入ArrayList链表里面
/**
*    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> arraylist = new ArrayList();
        //反转链表
            ListNode resulthead = null;
            ListNode ahead = listNode;
            ListNode before= null;
            if(ahead==null){
                return arraylist;
            }
            if(ahead.next==null){
                arraylist.add(ahead.val);
                return arraylist;
            }
            while(ahead!=null){
                ListNode next = ahead.next;
               if(next==null)
                   resulthead=ahead;
                ahead.next = before;
                before = ahead;
                ahead = next;
            }
            //保存链表数据进入arraylist中
            while(resulthead!=null){
                arraylist.add(resulthead.val);
                resulthead=resulthead.next;
             }
             
        return arraylist;
    }   
}

猜你喜欢

转载自blog.csdn.net/qq_42253147/article/details/86435239