问题描述
给定一个链表和两个数字 left
、right
,其中1 <= left <= right <= 链表节点数
,要求将 [left, right]
区间内的节点进行翻转。题目链接:**点我**
样例输入输出
输入:head = [1,3,5,7,9], left = 2, right = 4
输出:[1,7,5,3,9]
输入:head = [5], left = 1, right = 1
输出:[5]
问题解法
先遍历节点找到开始的地方,然后运用 LeetCode-206 翻转链表的解法对区间内的节点进行翻转。代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { int count = 2; ListNode prev = head; if (left == 1) { prev = new ListNode(-1000, head); count = 1; } ListNode p = prev.next; while (count < left) { prev = p; p = p.next; count++; } while (count < right) { ListNode temp = prev.next; prev.next = p.next; p.next = p.next.next; prev.next.next = temp; count++; } if (left == 1) { return prev.next; } return head; } }
|