LeetCode 剑指 Offer 06. 从尾到头打印链表
描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
题解
- List集合翻转
// List集合
class Solution {
public int[] reversePrint(ListNode head) {
List<Integer> list = new ArrayList<>();
while(head!=null){
list.add(head.val);
head = head.next;
}
Collections.reverse(list);
int [] res = new int[list.size()];
for(int i = 0;i<list.size();i++){
res[i] = list.get(i);
}
return res;
}
}
- 栈后进先出
/**
* 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<>();
while(head!=null){
stack.push(head);
head = head.next;
}
int [] res = new int [stack.size()];
int i = 0;
while(!stack.isEmpty()){
res[i]= stack.pop().val;
i++;
}
return res;
}
}
- 链表两次遍历
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
int count = 0;
ListNode node = head;
while(node!=null){
count++;
node = node.next;
}
int [] res = new int [count];
node = head;
while(node!=null){
count--;
res[count]= node.val;
node = node.next;
}
return res;
}
}