using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ public ListNode reverseBetween (ListNode head, int m, int n) { // write code here ListNode virtualHead = new ListNode(-1); virtualHead.next = head; ListNode cur = head; //m之前的节点 ListNode pre_Left = virtualHead; //m之后的节点 ListNode pre_Right = cur; for(int i = 1; i < m; i++) { pre_Left = cur; cur = cur.next; pre_Right = cur; } pre_Left.next = null; ListNode _pre,_cur; ReverseNode(cur, out _pre,out _cur, n- m +1 ); pre_Left.next = _pre; pre_Right.next = _cur; return virtualHead.next; } void ReverseNode(ListNode head,out ListNode _pre,out ListNode _cur,int cnt) { ListNode pre = null; ListNode next = null; for(int i = 1;i <= cnt ;i++) { next = head.next; head.next = pre; pre = head; head = next; } _pre = pre; _cur = head; } }
借助C#out将拆分区间的Index进行了返回,这样不需要提前遍历一遍获得Index,但还是不如直接边遍历边反转简单,还需要拼接两次头尾。