剑指 Offer 06. 从尾到头打印链表
题目:https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
解法一:Stack
/**
* 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[] nums=new int[stack.size()];
for (int i = 0; i < nums.length; i++) {
nums[i]=stack.pop().val;
}
return nums;
}
}
解法二:ArrayList
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ArrayList<ListNode> list=new ArrayList<>();
while(head!=null){
list.add(head);
head=head.next;
}
int len= list.size();
int[] nums=new int[len];
for (int i = 0; i < len; i++) {
nums[i]=list.get(len-i-1).val;
}
return nums;
}
}
解法三:无需Stack和ArrayList
public int[] reversePrint(ListNode head) {
//先获取链表长度,创建对应长度数组
ListNode currNode = head;
int len = 0;
while(currNode != null){
len ++;
currNode = currNode.next;
}
int[] result = new int[len];
//再次遍历链表,将值倒序填充至结果数组
currNode = head;
while(currNode != null){
result[len - 1] = currNode.val;
len --;
currNode = currNode.next;
}
return result;
}
解法三是先通过链表获取数组大小,从而逆序遍历数组赋值并返回。