题目来自LeetCode,链接:面试题06. 从尾到头打印链表。具体描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例:
输入:head = [1,3,2]
输出:[2,3,1]
首先可以利用栈保存遍历链表各节点得到的值,然后因为栈的特性(先进后出)出栈的时候得到的就是反向的各节点的值了,时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( n ) O(n) O(n)。
JAVA版代码如下:
/**
* 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> stack = new Stack<>();
while (head != null) {
stack.push(head.val);
head = head.next;
}
int size = stack.size();
int[] result = new int[size];
for (int i = 0; i < size; ++i) {
result[i] = stack.pop();
}
return result;
}
}
提交结果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/6782693cae88252cea783f46a707c7de.png)
然后可以用反转链表的方法,时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( 1 ) O(1) O(1)。
JAVA版代码如下:
/**
* 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[0];
}
int count = 0;
ListNode prev = head;
ListNode next = head.next;
head.next = null;
while (next != null) {
head = next;
next = head.next;
head.next = prev;
prev = head;
++count;
}
int[] result = new int[count + 1];
int i = 0;
while (head != null) {
result[i++] = head.val;
head = head.next;
}
return result;
}
}
提交结果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/82ea7b41e88e386ac254c4ccb2d1a7f6.png)
Python版代码如下:
# 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]:
result = []
while head is not None:
result.append(head.val)
head = head.next
return result[::-1]
提交结果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/109d3d5525f60b5aae147898cec78f7e.png)