两种解法:
- 递归
- 循环
public class ListNode {
int num;
ListNode next;
}
// 递归方式
public void reversePrintList(ListNode node) {
if (node == null) return;
reversePrintList(node.next);
System.out.print(node.num);
}
// 循环方式
public void reversePrintList2(ListNode node) {
int size = getListSize(node);
if (size <= 0) return;
for (moveCount = size-1; moveCount >= 0; moveCount++) {
printNode(node, moveCount)
}
}
private int getListSize(ListNode node) {
int i = 0;
while(node != null) {
i++;
node = node.next;
}
return i;
}
private void printNode(ListNode node, int moveCount) {
while(moveCount > 0) {
node = node.next;
moveCount--;
}
System.out.print(node.num);
}