给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回反转后的链表。
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
解题思路:
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int left, int right) {
//1. 为了防止头节点被反转,建立一个虚拟节点,指向头节点
ListNode dummy = new ListNode(0, head);
//2. 找到需要反转首节点的前节点
ListNode preNode = dummy;
for(int i = 0; i < left - 1; i++) {
preNode = preNode.next;
}
//3. 需要反转的第一个节点
ListNode firstNode = preNode.next;
//4. 依次反转节点,即采用头插法插入
for(int i = 0; i < right - left; i++) {
ListNode nextNode = firstNode.next;
firstNode.next = nextNode.next;
nextNode.next = preNode.next;
preNode.next = nextNode;
}
return dummy.next;
}
}
时间复杂度:O(N)
空间复杂度:O(1)
如果对您有所帮助的话,请点个赞再退出吧!!!
原题链接:https://leetcode-cn.com/problems/reverse-linked-list-ii