题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
解题思路
解法一:栈
“先入后出”可以借助“栈”来实现。具体做法是从链表的头节点开始,依次将每个节点压入栈内,然后依次弹出栈内的元素并存储到数组中。
复杂性分析:
时间复杂度:O(n)。正向遍历一遍链表,然后从栈弹出全部节点,等于又反向遍历一遍链表。
空间复杂度:O(n)。额外使用一个栈存储链表中的每个节点。
解法二:递归
每访问到一个节点的时候,先递归输出它后面的节点,再输出该节点自身。
复杂度分析:
时间复杂度:O(n)。遍历链表,需要递归n次。
空间复杂度:O(n)。系统递归需要使用 O(n)的栈空间。
解法三:记录节点个数,遍历两次链表
设置一个变量,第一次遍历链表时记录节点个数n,然后创建一个n维数组,再从头遍历链表,从数组末端往前存入节点值,最后返回此数组即可。
复杂性分析:
时间复杂度:O(n)。需要遍历两遍链表。
空间复杂度:O(1)。没有使用额外空间(不算最后返回的结果数组)。
代码
解法一:栈
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]:
stack = []
node = head
while node:
stack.append(node.val)
node = node.next
res = []
while stack:
res.append(stack.pop())
return res
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<ListNode> stack = new Stack<ListNode>();
ListNode node = head;
while(node != null){
stack.push(node);
node = node.next;
}
int size = stack.size();
int[] res = new int[size];
for(int i=0; i<size; i++){
res[i] = stack.pop().val;
}
return res;
}
}
解法二:递归
Python代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def __init__(self):
self.res = []
def reversePrint(self, head: ListNode) -> List[int]:
if head:
if head.next:
self.reversePrint(head.next)
self.res.append(head.val)
return self.res
Java代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<Integer> temp = new ArrayList<Integer>();
public void recur(ListNode head){
if(head != null){
if(head.next != null){
recur(head.next);
}
temp.add(head.val);
}
//return temp;
}
public int[] reversePrint(ListNode head) {
recur(head);
int size = temp.size();
int[] res = new int[size];
for(int i=0; i<size; i++){
res[i] = temp.get(i);
}
return res;
}
}
解法三:记录节点个数,遍历两次链表
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]:
count = 0
node = head
while node:
count += 1
node = node.next
res = [0]*count
p = head
for i in range(count-1, -1, -1):
res[i] = p.val
p = p.next
return res
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) {
ListNode node = head;
int count = 0;
while(node != null){
count++;
node = node.next;
}
int[] res = new int[count];
ListNode p = head;
for(int i=count-1; i>=0; i--){
res[i] = p.val;
p = p.next;
}
return res;
}
}