逆序打印单向链表

来源:互联网 发布:网易云课堂 mac 编辑:程序博客网 时间:2024/04/29 16:38

问题:

给你一个单向链表,比如 a -> b -> c -> d -> e -> f, 把这个链表逆序打印出来,即:f -> e -> d ->c ->b ->a

思路:

方法1:遍历链表,把每一个值按照顺序放在一个stack 里,当遍历完毕以后,再把 stack 里的每一个node取出来打印。

方法2:利用递归的原理,先遍历到链表的最后一个节点,然后再打印。这样做本质上和方法1是一样的。

 class Node {String value;Node next = null;public Node(String value) {this.value = value;}}
public static void reversePrint(Node node) {if (node == null) return;if (node.next != null) {reversePrint(node.next);}System.out.println(node.value);}

如果顺序打印,方法为:

public static void printList(Node node) {if (node == null) return;System.out.println(node.value);if (node.next != null) {printList(node.next);}}

public static ListNode reverse(ListNode head) {if (head == null) return null;ListNode n = head.next;ListNode previous = head;head.next = null;while(n != null) {ListNode nn = n.next;n.next = previous;previous = n;n = nn;}return previous;}

转载请注明出处:http://blog.csdn.net/beiyetengqing



原创粉丝点击