逆序打印单向链表
来源:互联网 发布:网易云课堂 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
- 逆序打印单向链表
- 单向链表逆序
- 单向链表逆序
- 单向链表逆序
- 单向链表逆序
- 单向链表逆序
- 单向链表逆序
- 单向链表逆序
- 单向链表逆序
- 单向链表逆序
- 算法-单向链表逆序
- 单向链表逆序输出
- 单向链表逆序 图解
- 单向链表逆序问题
- 单向链表新增逆序
- 将单向链表逆序
- 逆序打印链表
- 逆序打印链表
- 计算机图形学中的基本概念总结
- 推荐一本书——《浪潮之巅》
- HTML Select 操作
- 常回博客看看
- JSP连接Access
- 逆序打印单向链表
- 推荐一本书——《PHP语言精粹》
- 优化器(Optermizer)
- 收藏 不显示删除回复显示所有回复显示星级回复显示得分回复 有人看了第一句就哭了
- C# WinForm窗体中有控件时keyDown事件问题处理方式
- 用VC资源动态链接库解决国际化问题
- BaiAPI 简单示例
- 背包问题之0-1背包(三)
- 循环压缩某个目录