
输入一个链表的头节点,从尾到头反过来打印出每个节点的值,链表定义如下:
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 32 33 34 35 36 37 38 39 40
|
public class { public static void main(String[] args) { ListNode head = new ListNode("a"); ListNode node1 = new ListNode("b"); ListNode node2 = new ListNode("c"); ListNode node3 = new ListNode("d"); head.next = node1; node1.next = node2; node2.next = node3; PrintReversingly_Iteratively(head); }
public static void PrintReversingly_Iteratively(ListNode node) { Stack<ListNode> nodeStack = new Stack<>(); while (node != null) { nodeStack.push(node); node = node.next; } while (!nodeStack.isEmpty()) { ListNode tempNode = nodeStack.pop(); System.out.println(tempNode.value); } } }
|
近期评论