从头到尾打印链表_JAVA_较难
从尾到头打印链表
http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
递归
import java.util.ArrayList; public class Solution { private ArrayList<Integer> list = new ArrayList(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { if(listNode == null) { return list; } printListFromTailToHead(listNode.next); list.add(listNode.val); return list; } }
反转链表
import java.util.ArrayList; public class Solution { private ArrayList<Integer> list = new ArrayList(); public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> list = new ArrayList(); ListNode pre = new ListNode(-1), post; // 反转链表 while(listNode != null) { post = listNode.next; listNode.next = pre; pre = listNode; listNode = post; } // 存值 listNode = pre; while(listNode != null && listNode.next != null) { list.add(listNode.val); listNode = listNode.next; } return list; } }