Leetcode: Reverse Linked List
2015-12-15 11:15
302 查看
Reverse a singly linked list.
Don't forget to consider the case where the linked list is empty
Time: O(2N), Space: O(1)
/** * 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) return null; ListNode dummy = new ListNode(-1); dummy.next = head; ListNode end = dummy; while (end.next != null) { end = end.next; } while (dummy.next != end) { ListNode cur = dummy.next; ListNode next = cur.next; cur.next = end.next; end.next = cur; dummy.next = next; } return dummy.next; } }
基本迭代
Time: O(N), Space: O(1)
public class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode p1 = head; ListNode p2 = p1.next; while(p2 != null){ ListNode tmp = p2.next; p2.next = p1; p1 = p2; p2 = tmp; } head.next = null; return p1; } }
基本递归
Time: O(N), Space: O(N)递归栈大小
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { ListNode newHead; public ListNode reverseList(ListNode head) { reverse(head); return newHead; } private ListNode reverse(ListNode n){ if( n == null || n.next == null){ newHead = n; } else { ListNode prev = reverse(n.next); prev.next = n; } return n; } }
相关文章推荐
- Android实战 - 音心音乐播放器 (开启篇)
- leetcode Valid Parentheses
- servlet 总结
- STM32芯片开发之添加外置NOR FALSH扩展代码空间
- 【转】Pro Android学习笔记(七):了解Content Provider(下上)
- [Spring] Spring配置文件中特殊字符的规定
- Kinect for Windows SDK开发入门(三):基础知识 下
- 使用ip地址访问不能上传文件到服务器数据库的解决方案
- request.setCharacterEncoding() 和 response.setContentType()
- iOS开发break,continue,return的区别
- Linux命令--用户用户组管理
- iOS-NSUserDefaults
- Toast用法
- Android wakelock机制
- Android开发所需工具
- flyway初始化脚本存在默认特殊字符的问题处理
- android AsyncTask异步调用方法
- 一位上了一个大的互联网公司笔试题分享
- linux ntp时间同步
- 【转】Pro Android学习笔记(六):了解Content Provider(中)