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
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
A是A出来了,不过写的略挫,有点懒,不太想改了
1 public class Solution { 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 ListNode headNode = new ListNode(0); 4 headNode.next = head; 5 head = headNode; //插入一个头结点 6 7 ListNode toEnd = head; 8 ListNode toInsert = head; 9 10 for(int i = 1; i < m; i++){ //找到插入点 11 toInsert = toInsert.next; 12 toEnd = toEnd.next; 13 }//for 14 if(m < n){ //第一个采用头结点插入法插入的 15 toEnd = toEnd.next; 16 ListNode temp = new ListNode(toEnd.val); 17 toInsert.next = temp; 18 }//if 19 20 int count = n - m; 21 while(count > 0){ //采用头插法 22 toEnd = toEnd.next; 23 ListNode temp = new ListNode(toEnd.val); 24 temp.next = toInsert.next; 25 toInsert.next = temp; 26 count--; 27 }//while 28 29 if(m < n) 30 { 31 while(toInsert.next != null) 32 toInsert = toInsert.next; 33 toInsert.next = toEnd.next; 34 } 35 36 head = head.next; 37 return head; 38 } 39 }