从尾到头打印链表
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
package SwordOffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;
/** * @author jinhuajian * @data 2018年12月27日---上午11:20:21 * @blog https://me.csdn.net/qq_37119939 */
public class Solution_03 {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
ArrayList<Integer> al = new ArrayList<Integer>();
if (listNode == null)
return al;
Stack<Integer> stack = new Stack<Integer>();
ListNode head = listNode;
while (listNode != null) {
stack.push(listNode.val);
listNode = listNode.next;
}
while (!stack.isEmpty()) {
al.add(stack.pop());
}
return al;
}
// 递归版
public ArrayList<Integer> printListFromTailToHead_01(ListNode listNode) {
ArrayList<Integer> al = new ArrayList<Integer>();
printHead(listNode, al);
return al;
}
public ArrayList<Integer> printListFromTailToHead_02(ListNode listNode) {
ArrayList<Integer> al = new ArrayList<Integer>();
if (listNode == null)
return al;
printListFromTailToHead_02(listNode.next);
return al;
}
public void printHead(ListNode head, ArrayList<Integer> a) {
if (head == null)
return;
printHead(head.next, a);
a.add(head.val);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode ln = new ListNode(1);
ln.next = new ListNode(2);
ln.next.next = new ListNode(3);
ln.next.next.next = new ListNode(19);
Solution_03 s = new Solution_03();
ArrayList<Integer> l = s.printListFromTailToHead(ln);// 必须带泛型<Integer>
ArrayList<Integer> l1 = s.printListFromTailToHead_01(ln);
// 遍历ArrayList的四种方法
for (Integer arr : l) {
System.out.print(arr + " ");
}
System.out.println();
for (int i = 0; i != l.size(); i++) {
System.out.print(l.get(i) + " ");
}
System.out.println();
Iterator<Integer> it = l.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
for (Iterator<Integer> it1 = l1.iterator(); it1.hasNext();) {
System.out.print(it1.next() + " ");
}
}
}