LeetCode OJ 92. Reverse Linked List II
2016-04-18 17:09
381 查看
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
return
相对于单纯的链表转置,这个问题需要把链表的一部分做反转。并要求就地反转而且只遍历一次。我的想法是吧链表看成3个部分:list1->list2->list3其中list2代表要反转的部分。我们先找到list2的开始,然后反转list2变为newlist2,然后把链表连接起来list1->newlist2->list3。实现起来还是比较简单的,但是要注意一些边界条件。这些边界条件通过m/n来控制。代码如下:
For example:
Given
1->2->3->4->5->NULL, m = 2 and n = 4,
return
1->4->3->2->5->NULL.
相对于单纯的链表转置,这个问题需要把链表的一部分做反转。并要求就地反转而且只遍历一次。我的想法是吧链表看成3个部分:list1->list2->list3其中list2代表要反转的部分。我们先找到list2的开始,然后反转list2变为newlist2,然后把链表连接起来list1->newlist2->list3。实现起来还是比较简单的,但是要注意一些边界条件。这些边界条件通过m/n来控制。代码如下:
public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(head==null || head.next==null || m==n || m>n) return head; ListNode nhead = new ListNode(0); nhead.next = head; ListNode start = nhead; ListNode end = null; int count = 0; while(start.next!=null && count<m-1){ count++; start = start.next; } ListNode a = null; ListNode b = start.next; ListNode c = null; end = b; while(b!=null && count<n){ c = b.next; b.next = a; a = b; b = c; count++; } start.next = a; end.next = b; return nhead.next; } }
相关文章推荐
- FMX对象释放
- VisualVM连接远程Java进程
- 24点游戏算法
- java学习笔记(一)
- C#学习笔记二 引用参数和值参数
- 挺好的 过程里面有些可取之处
- SharedPreferences
- 新绑定业务修改点
- Android面试及使用技术点总结
- 应用ModelState和Data Annotation做服务器端数据验证
- C-IDE使用帮助
- MapReduce计算框架
- Android插件化框架研究-DroidPlugin
- createrepo
- Android Studio 如何打JAR包
- recyclerview显示的宽度只有屏幕的一部分
- 对DllRegisterServer的调用失败,错误代码为0x8007005的解决办法,注册控件
- java学习 集合之LinkedList
- 简单的留言板
- Masonry示例Examples使用cocoapods命令pod install之后报错处理