当前位置:网站首页>Sword finger offer 06 Print linked list from end to end

Sword finger offer 06 Print linked list from end to end

2022-07-05 08:21:00 Programmer Xiao Li

subject :

Enter the head node of a linked list , Return the value of each node from the end to the end ( Return with array ).

Example 1:

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

Limit :

0 <= Chain length <= 10000

Ideas :

Use the stack to complete the traversal of the linked list , Finally, play the stack in turn to get the results .

/**
 * 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> stack = new Stack<>();
        int counter = 0;
        while(head != null){
            counter++;
            stack.push(head);
            head = head.next;
        }

        int[] array = new int[counter];
        for (int i = 0; i < counter; i++){
            array[i] = stack.pop().val;
        }

        return array;
    }
}

 

原网站

版权声明
本文为[Programmer Xiao Li]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050816402795.html