链表一般是从头到尾打印比较方便,本题要从尾到头打印,可以想成是后进先出,是一个栈结构。而递归就是一个栈结构。
- 递归的方法
/**
- public class ListNode {
- int val;
- ListNode next = null;
- 5. 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;
}
}
记住链表的定义,ListNode.next, ListNode.val
往链表里添加值,ListNode.add(l.val)
2.头插法,得到逆序的链表
头结点和第一个节点的区别:
- 头结点是在头插法中使用的一个额外节点,这个节点不存储值;
- 第一个节点就是链表的第一个真正存储值的节点。
- 1->2->3,头节点先指向1,然后将2指向1,头节点再指向1,以此类推。
/**
* 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 memo=listNode.next;
listNode.next=head.next;
head.next=listNode;
listNode=memo;
}
ArrayList<Integer> ret = new ArrayList<>();
head=head.next;//注意这里头节点是空的,要从头节点的下一个开始
while(head!=null){
ret.add(head.val);
head = head.next;
}
return ret;
}
}
3.使用栈
/**
* 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) {
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;
}
}
java中栈的几种方法有
import java.util.*;
public class StackDemo {
static void showpush(Stack<Integer> st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack<Integer> st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack<Integer> st = new Stack<Integer>();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}