题解 | 牛群的重新排列
牛群的重新排列
https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838
- 请直接参照牛群的重新分组。
import java.util.*; public class Solution { public void reverseList(ListNode head) { ListNode pre = null, cur = head; while (cur != null) { final ListNode nxt = cur.next; cur.next = pre; pre = cur; cur = nxt; } } public ListNode reverseBetween (ListNode head, int left, int right) { ListNode guard = new ListNode(0); guard.next = head; int cnt = 0; ListNode preLeft = guard, cur = head; while(cur != null) { cnt += 1; if (cnt < left) { preLeft = cur; cur = cur.next; } else if (cnt < right) { cur = cur.next; } else { final ListNode nxt = cur.next; cur.next = null; reverseList(preLeft.next); final ListNode rangeTail = preLeft.next; preLeft.next = cur; rangeTail.next = nxt; break; } } return guard.next; } }