一、题目描述:
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
二、解题思路:
这道题类似于反向输出链表的题目。有两种思路:
①递归解决,可以反向输出。(根据递归的特点)
②充分利用数据结构:栈的“后进先出”实现
③利用三个指针来反向输出链表(pre,current,next)
三、代码
①递归版本
/**
* public class ListNode {
* int val;
* ListNode next = null;
*
* ListNode(int val) {
* this.val = val;
* }
* }
*
*/
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> arrayList = new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if (listNode != null) {
if (listNode.next != null) {
printListFromTailToHead(listNode.next);
}
arrayList.add(listNode.val);
}
return arrayList;
}
}
②栈结构版本
/**
* 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<Integer>();
while(listNode!=null){
stack.push(listNode.val);
listNode=listNode.next;
}
ArrayList<Integer> list=new ArrayList<Integer>();
while(!stack.isEmpty()){
list.add(stack.pop());
}
return list;
}
}
③三个指针
/**
* 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 pre = null;
ListNode current = listNode;
ListNode reverseHead = null;
//下面这部分是把整个链表反转
if (current != null) {
while (current != null) {
ListNode next = current.next;
if (next == null) {
reverseHead = current;
}
current.next=pre;
pre = current;
current = next;
}
current = reverseHead;
}
ArrayList<Integer> arrayList = new ArrayList<Integer>();
while (current!= null) {
arrayList.add(current.val);
current = current.next;
}
return arrayList;
}
}
题外话:牛客网的编辑器真的佩服了。。。(反正是需要细致的注意啦~~)
比如函数名从本地编辑器粘贴过来的时候是不是错了。。。
这样子就可以(上面)
而中间一行加有空格就不可以!