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.
插入法,插到前一个结点后面,然后指针后移
Source
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode a = new ListNode(0); //加头结点,注意头结点的逆置
a.next = head;
ListNode q = a;
ListNode p = q, k = q;
int flag = n - m + 1;
if(m == n) return head; //***
for(int i = 0; i < m - 1;i++){
q = q.next;
}
while(flag != 0){
p = q;
for(int i = 0; i < flag ;i++){
k = p;
p = p.next;
}
k.next = p.next; //链表不能断
p.next = q.next;
q.next = p;
q = q.next; //每插入一个后移一位 如果不移则和以前一样
flag --;
}
return a.next;
}
}
Test
public static void main(String[] args){
ListNode a = new ListNode(1);
a.next = new ListNode(2);
// a.next.next = new ListNode(3);
// a.next.next.next = new ListNode(4);
// a.next.next.next.next = new ListNode(5);
ListNode b = new Solution().reverseBetween(a, 1, 2);
while(b != null){
System.out.print(b.val);
b = b.next;
}
}