当前位置:网站首页>One brush 313 sword finger offer 06 Print linked list from end to end (E)

One brush 313 sword finger offer 06 Print linked list from end to end (E)

2022-04-23 15:40:00 Tang and Song Dynasties

 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 :
 One way linked list , Want to take value from back to front , Or go through it first and remember lenth Then store in reverse order ,
 Or use the stack to temporarily store and then pop up . Always traverse the container twice 

 The direction is opposite to the original direction , Lenovo stack 
 Go through... Remember first size  Then traverse in sequence   But write in reverse order into the array 
--------------
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
    
    public int[] reversePrint(ListNode head) {
    
        ListNode index = head; 
        int count = 0;
        while (index != null) {
    // Traverse once   remember count
            index = index.next;
            count++;
        }
        index = head;// Reinitialize  index Point to the head node 
        int[] res = new int[count];// Result set 
        while (index != null) {
    // Traverse 
            res[--count] = index.val;// Write forward from the end of the array 
            index = index.next;
        }
        return res;
    }
}

LC

版权声明
本文为[Tang and Song Dynasties]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231535203797.html