面试题6:从尾到头打印链表
输入一个链表的头节点,从尾到头反过来打印出每个节点的值。链表节点的定义如下:
class Node {
int key;
Node next;
}
解法一:
遍历链表,并使用栈来保存节点信息,遍历结束后,从栈中输出结果。
package Question06;
import java.util.Stack;
public class T01 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 5, 3, 5, 6, 7, 5, 3};
LinkedList linkedList = new LinkedList(arr);
linkedList.add(9);
linkedList.printListFromLast();
}
}
class LinkedList {
Node head = new Node(-1);
public LinkedList(int[] arr) {
Node cur = head;
for(int i = 0; i < arr.length; i++) {
Node temp = new Node(arr[i]);
cur.next = temp;
cur = cur.next;
}
}
public void add(int key) {
Node cur = head;
while(cur.next != null) cur = cur.next;
Node temp = new Node(key);
temp.next = cur.next;
cur.next = temp;
}
public void printListFromLast() {
Stack<Integer> stack = new Stack<>();
Node cur = head.next;
while(cur != null) {
stack.push(cur.key);
cur = cur.next;
}
while(!stack.empty()) {
System.out.println(stack.pop());
}
}
}
class Node {
public int key;
public Node next;
public Node(int key) {
this.key = key;
}
}
解法二:使用递归来操作
public void printListFromLast2(Node temp) {
if(temp == null) return ;
printListFromLast2(temp.next);
if(temp != head) System.out.println(temp.key);
}