6. The print head from the end of the list [Java]

Title Description online programming

From the tail to the head in turn prints out the value of each node

 

answer

First interpolation list may be reversed

/**
*    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> ret=new ArrayList<>();
       ListNode dummy=new ListNode(-1);
       ListNode cur=listNode;
        while(cur!=null){
            ListNode next=cur.next;
            cur.next=dummy.next;
            dummy.next=cur;
            
            cur=next;
        }
        cur=dummy.next;
        while(cur!=null){
           ret.add(cur.val);
            cur=cur.next;
        }
        return ret;
    }
}

 

Guess you like

Origin www.cnblogs.com/zslhg903/p/11203295.html