本文主要是介绍【剑指Offer 06】从尾到头打印链表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
递归
/**
* 剑指 Offer 06. 从尾到头打印链表
* 思路:递归或栈
* */
public class Solution {
public int[] reversePrint(ListNode head) {
return reverse(head, 0, null);
}
private int[] reverse(ListNode node, int count, int[] result) {
if (node == null) {
return new int[count];
}
result = reverse(node.next, count + 1, null);
result[result.length - count - 1] = node.val;
return result;
}
}
栈
public class Solution2 {
public int[] reversePrint(ListNode head) {
Deque<Integer> stack = new ArrayDeque<>();
ListNode node = head;
while (node != null) {
stack.push(node.val);
node = node.next;
}
return toArray(stack);
}
private int[] toArray(Deque<Integer> stack) {
int[] array = new int[stack.size()];
for (int i = 0; i < array.length; i++) {
array[i] = stack.pop();
}
return array;
}
}
这篇关于【剑指Offer 06】从尾到头打印链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!