Sword refers to offer.06 Print the linked list from end to beginning

Enter the head node of a linked list, and return the value of each node from the end to the beginning (return with an array).

Example 1:

Input: head = [1,3,2]
 Output: [2,3,1]

answer:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
            Stack<ListNode> s=new Stack<>();
            
            while(head!=null){
               s.push(head);
                head=head.next; 
            }
                int size=s.size();
            int[] array=new int[size];
            for(int i=0;i<size;i++){     
               array[i]=s.pop().val; 
               }
            return array;
    }
}

 

Guess you like

Origin blog.csdn.net/qq_44624536/article/details/114951688