LeetCode 206. Reverse Linked List(翻转链表)
2016-05-04 08:22
337 查看
原题网址:https://leetcode.com/problems/reverse-linked-list/
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
方法一:迭代。
方法二:递归。
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
方法一:迭代。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null) return head; ListNode current = head.next; ListNode prev = head; prev.next = null; while (current.next != null) { ListNode next = current.next; current.next = prev; prev = current; current = next; } current.next = prev; return current; } }
方法二:递归。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { private ListNode reversed; private void reverse(ListNode prev, ListNode node) { if (node == null) return; reversed = node; ListNode next = node.next; node.next = prev; reverse(node, next); } public ListNode reverseList(ListNode head) { if (head == null || head.next == null) return head; reverse(null, head); return reversed; } }
相关文章推荐
- 50道题
- 浅谈java向上转型和乡下转型
- Win10商店恢复详情 PC和手机可以正常访问和下载应用
- volatile修饰符
- 关于URL
- Java LinkedList源码剖析
- 使用 MySQL 查找附近的位置
- 异步vs非阻塞
- DB2 数据库之数据打平函数
- Java 并发编程:线程间的协作(wait/notify/sleep/yield/join)
- Java代码中单例模式总结
- mysql 登录、退出
- Spark笔记一之启动、简单RDD、提交、测试
- 最小生成树(prime算法、kruskal算法) 和 最短路径算法(floyd、dijkstra)
- MVC5+EF6 入门完整教程12--灵活控制Action权限
- Unity3D入门(rolling ball)——学习笔记
- jQuery的ajax使用场景讨论(c#)
- tda2822功放
- ASP.NET 状态管理(视图状态 ViewState)
- 打电话、发短信、web以及发邮件