92.Reverse Linked List II
题目大意:翻转链表中从m到n的结点,其他位置保持不变。
法一:与61类似,只是61是轮询翻转,而这题是抽一部分翻转,所以可以将链表分成三部分,前面,中间,后面,对前面和后面只需要遍历即可,对中间则进行翻转。代码如下(耗时4ms):
1 public ListNode reverseBetween(ListNode head, int m, int n) { 2 ListNode pre = null, res = head; 3 //找到前面的最末位节点 4 for(int i = 1; i < m; i++) { 5 if(pre == null) { 6 pre = head; 7 res = pre; 8 } 9 else { 10 pre.next = head; 11 pre = head; 12 } 13 head = head.next; 14 } 15 //处理中间节点 16 ListNode mi = null, miPost = mi; 17 for(int i = m; i <= n; i++) { 18 if(mi == null) { 19 mi = head; 20 miPost = mi; 21 head = head.next; 22 } 23 else { 24 ListNode tmp = head; 25 head = head.next; 26 tmp.next = mi; 27 mi = tmp; 28 } 29 } 30 if(pre != null) { 31 //前面连接中间 32 pre.next = mi; 33 //中间连接后面 34 miPost.next = head; 35 } 36 else { 37 res = mi; 38 miPost.next = head; 39 } 40 return res; 41 }