1、使用栈:
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arr = new ArrayList();
Stack<Integer> stack = new Stack();
while(listNode != null){
stack.push(listNode.val);
listNode = listNode.next;
}
while(!stack.isEmpty()){
int value = stack.pop();
arr.add(value);
}
return arr;
}
}
别忘了导入包:java.util.Stack;
Stack的声明别忘了类型:
Stack stack = new Stack();
它的方法:push()和pop();
2、使用递归:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arr = new ArrayList();
if(listNode == null){
return arr;
}
arr = printListFromTailToHead(listNode.next);
arr.add(listNode.val);
return arr;
}
}
3、使用Collections.reverse()
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arr = new ArrayList();
while(listNode != null){
arr.add(listNode.val);
listNode = listNode.next;
}
Collections.reverse(arr);
return arr;
}
}
4、使用头插法
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> arr = new ArrayList();
ListNode head = new ListNode(-1);
while(listNode != null){
//注意这里
ListNode pre = new ListNode(listNode.val);
pre.next = head.next;
head.next = pre;
listNode = listNode.next;
}
ListNode p = head.next;
while(p != null){
arr.add(p.val);
p = p.next;
}
return arr;
}
}
使用头插法,可以让它的顺序反过来!
本文介绍四种不同的方法来实现链表元素的逆序打印:使用栈、递归、Collections.reverse()方法及头插法,并提供了每种方法的详细代码实现。
277

被折叠的 条评论
为什么被折叠?



