题目:
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
.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head.next==null||head==null){return head;}
//带头节点
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode pre=dummy;
//找到起始交换的前一个节点
for(int i=0;i<m-1;i++){
pre=pre.next;
}
//为交换的第一个节点
ListNode cur=pre.next;
//cur的下一个节点
ListNode curNext=cur.next;
//开始交换位置
for(int i=0;i<n-m;i++){
//采用类似头结点的置换方式,将当前需要交换的节点直接插入到pre的下一个
cur.next=curNext.next;
curNext.next=pre.next;
pre.next=curNext;
//下一个交换节点
curNext=cur.next;
}
return dummy.next;
}
}