LeetCode OJ 92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
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来控制。代码如下:
1 public class Solution { 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 if(head==null || head.next==null || m==n || m>n) return head; 4 ListNode nhead = new ListNode(0); 5 nhead.next = head; 6 ListNode start = nhead; 7 ListNode end = null; 8 int count = 0; 9 while(start.next!=null && count<m-1){ 10 count++; 11 start = start.next; 12 } 13 ListNode a = null; 14 ListNode b = start.next; 15 ListNode c = null; 16 end = b; 17 while(b!=null && count<n){ 18 c = b.next; 19 b.next = a; 20 a = b; 21 b = c; 22 count++; 23 } 24 start.next = a; 25 end.next = b; 26 return nhead.next; 27 } 28 }