在O(n) 时间复杂度,O(1)空间复杂度内反转单链表
2015-07-28 17:31
423 查看
在LeetCode中看到判断回文的程序:https://leetcode.com/problems/palindrome-linked-list/
里面用单链表来存储数据,先反转前半部分的单链表,然后分别从 表头 和 中间链表位置处 开始比较元素。
反转单链表的代码如下:
里面用单链表来存储数据,先反转前半部分的单链表,然后分别从 表头 和 中间链表位置处 开始比较元素。
反转单链表的代码如下:
1 private ListNode reverseList(ListNode head, int length){ 2 if(head == null) 3 return null; 4 ListNode currentNode, preNode; 5 currentNode = preNode = head; 6 ListNode nextNode = head.next; 7 head.next = null; 8 for(int i = 1; i < length; i++){ 9 if(nextNode != null){ 10 currentNode = nextNode; 11 nextNode = nextNode.next; 12 currentNode.next = preNode; 13 preNode = currentNode; 14 } 15 } 16 return currentNode; 17 }
相关文章推荐
- hive 数据操作(二)
- 游戏开发之随机概率的选择算法
- Win7与虚拟机VMware下运行的Ubuntu共享文件夹
- 游戏开发一般分为哪几类?
- 234 Palindrome Linked List
- 红黑树的理解说明(插入)
- 一个简单的python连接池,以及DBUtil.PooledDB的使用
- c3p0连接池
- iOS面试题--网络--如何处理多个网络请求的并发的情况
- Windows Message Queue(优先队列)
- Linux命令详解 -- date
- 差分约束系统
- 【Android】保存Fragment切换状态
- JDBC中Statement与PreparedStatement的区别
- java 微信支付所需MD5加密类
- [译]Python编写虚拟解释器
- map容器按value值排序
- Populating Next Right Pointers in Each Node
- Android的屏幕切换动画
- 黑马程序员--学习C语言结构体