面试题5:从尾到头打印链表

输入一个链表的头结点,从尾到头反过来打印每个节点。

解答:

  1. 用栈来打印。(遍历一遍入栈,然后对栈做出栈操作)
  2. 递归就是一个栈。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package offer;
public class {
static class ListNode{
public ListNode(int key, ListNode next) {
this.key=key;
this.next=next;
}
int key;
ListNode next;
}
static void printList(ListNode head){
if(head!=null){
if(head.next!=null){
printList(head.next);
}
System.out.println(head.key);
}
}
public static void main(String[] args) {
ListNode n5= new ListNode(5, null);
ListNode n4= new ListNode(4, n5);
ListNode n3= new ListNode(3, n4);
ListNode n2= new ListNode(2, n3);
ListNode head= new ListNode(1, n2);
printList(head);
}
}