剑指offer 03:从尾到头打印链表

时间:2023-03-08 15:48:56

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

递归法

/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> ret = new ArrayList<>();
if(listNode != null){
ret.addAll(printListFromTailToHead(listNode.next));
ret.add(listNode.val);
}
return ret;
}
}

/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution{
public ArrayList<Integer> printListFromTailToHead(ListNode listNode){
Stack<Integer> stack = new Stack<>();
while(listNode != null){
stack.add(listNode.val);
listNode = listNode.next;
}
ArrayList<Integer> ret = new ArrayList<>();
while(!stack.isEmpty())
ret.add(stack.pop());
return ret;
}
}

头插法

/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution{
public ArrayList<Integer> printListFromTailToHead(ListNode listNode){
ListNode head = new ListNode(-1);
while(listNode != null){
ListNode next = listNode.next;
listNode.next = head.next;
head.next = listNode;
listNode = next;
} ArrayList<Integer> ret = new ArrayList<>();
head = head.next;
while(head != null){
ret.add(head.val);
head = head.next;
}
return ret;
}
}