面试题6:从尾到头打印链表
题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。
import java.util.Stack;
public class PrintListInReversedOrder {
private static class ListNode {
ListNode next = null;
int value;
ListNode(int value) {
this.value = value;
}
}
private static ListNode createListNode(int value) {
return new ListNode(value);
}
private static void connectListNode(ListNode node1, ListNode node2) {
node1.next = node2;
}
private static void printListReversinglyIteratively(ListNode head) {
Stack<ListNode> nodes = new Stack<>();
ListNode node = head;
while (node != null) {
nodes.push(node);
node = node.next;
}
while (!nodes.empty()) {
node = nodes.peek();
System.out.print(node.value);
nodes.pop();
}
}
private static void printListReversinglyRecursively(ListNode head) {
if (head != null) {
if (head.next != null) {
printListReversinglyRecursively(head.next);
}
System.out.print(head.value);
}
}
private static void printList(ListNode head) {
if (head != null) {
System.out.print(head.value);
printList(head.next);
}
}
private static void test(ListNode head) {
printList(head);
System.out.println();
printListReversinglyIteratively(head);
System.out.println();
printListReversinglyRecursively(head);
System.out.println();
}
private static void test1() {
System.out.println("Test1 begins.");
ListNode node1 = createListNode(1);
ListNode node2 = createListNode(2);
ListNode node3 = createListNode(3);
ListNode node4 = createListNode(4);
ListNode node5 = createListNode(5);
connectListNode(node1, node2);
connectListNode(node2, node3);
connectListNode(node3, node4);
connectListNode(node4, node5);
test(node1);
destroyList(node1);
}
private static void destroyList(ListNode head) {
if (head != null) {
destroyList(head.next);
head = null;
}
}
private static void test2() {
System.out.println("Test2 begins");
ListNode node = createListNode(1);
test(node);
destroyList(node);
}
private static void test3() {
System.out.println("Test3 begins");
test(null);
}
public static void main(String[] args) {
test1();
test2();
test3();
}
}
运行结果:
Test1 begins.
12345
54321
54321
Test2 begins
1
1
1
Test3 begins
- 面试的时候,链表结构好像会给出来,不用自己建,这我就放心了,不用自己弄测试用例。