Enter the first node of a linked list and return the value of each node from end to end (as an array).
Example 1:
Enter: head = [1.3.2] output: [2.3.1]
Copy the code
Limitations:
0 <= List length <= 10000
solution
The stack. Or some other way, see solution.
Python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self.x) : #self.val = x
# self.next = None
class Solution:
def reversePrint(self.head: ListNode) - >List[int] :res = []
while head:
res.append(head.val)
head = head.next
return res[::-1]
Copy the code
Java
- The stack to achieve
/** * 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<Integer> s = new Stack<>();
while(head ! =null) {
s.push(head.val);
head = head.next;
}
int[] res = new int[s.size()];
int i = 0;
while(! s.isEmpty()) { res[i++] = s.pop(); }returnres; }}Copy the code
- Compute the list length N, then create a result array of length N. The list is finally traversed, storing the node values in sequence on the array (from back to front).
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; }} * * /
class Solution {
public int[] reversePrint(ListNode head) {
if (head == null) return new int[]{};
// Calculate the list length n
int n = 0;
ListNode cur = head;
while(cur ! =null) {
++n;
cur = cur.next;
}
int[] res = new int[n];
cur = head;
while(cur ! =null) {
res[--n] = cur.val;
cur = cur.next;
}
returnres; }}Copy the code
C++
- The stack to achieve
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> stk;
vector<int> ans;
ListNode *p = head;
while (p) {
stk.push(p->val);
p = p->next;
}
while(! stk.empty()) { ans.push_back(stk.top()); stk.pop(); }returnans; }};Copy the code