LeetCode92. 反转链表 II🌟🌟🌟中等
课后作业
问题描述
原文链接:92. 反转链表 II
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回反转后的链表 。
示例 1:

输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
提示:
- 链表中节点数目为
n 1 <= n <= 500-500 <= Node.val <= 5001 <= left <= right <= n
代码实现
Java
/**
* 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 {
ListNode last = null;
public ListNode reverseBetween(ListNode head, int left, int right) {
//left = 1
if(left == 1){
return reverseThN(head, right);
}
//1~left - 1
head.next = reverseBetween(head.next, left - 1, right - 1);
return head;
}
// 反转第1~n的节点
ListNode reverseThN(ListNode head, int n){
if(n == 1){
last = head.next;
return head;
}
ListNode newHead = reverseThN(head.next, n - 1);
head.next.next = head;
head.next = last;
return newHead;
}
}
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
last = None
def reverseBetween(self, head, left, right):
"""
:type head: ListNode
:type left: int
:type right: int
:rtype: ListNode
"""
if left == 1:
return self.reverseThN(head, right)
head.next = self.reverseBetween(head.next, left - 1, right - 1)
return head
def reverseThN(self, head, n):
if n == 1:
self.last = head.next
return head
newHead = self.reverseThN(head.next, n - 1)
head.next.next = head
head.next = self.last
return newHead
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
private:
ListNode* last = nullptr;
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if (left == 1) {
return reverseThN(head, right);
}
head->next = reverseBetween(head->next, left - 1, right - 1);
return head;
}
ListNode* reverseThN(ListNode* head, int n) {
if (n == 1) {
last = head->next;
return head;
}
ListNode* newHead = reverseThN(head->next, n - 1);
head->next->next = head;
head->next = last;
return newHead;
}
};
Go
评论(10)
打卡
先化为前right项,再让left逐渐为1,采用递归的思想
没有采用递归erverseBetweeen,
直接通过left定位到要反转的起始位置
将反转后的链表接起来
打卡
结束条件right 1,,,不能是head.next null
并且自己漏了last = head.next;
写错了,明天再写一遍
class Solution {
private:
void reverseLinkedlist(ListNode*head){
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode*dummyHead=new ListNode(0);
dummyHead->next=head;
};
打卡,递归法二刷再看
class Solution {
private:
//翻转链表
void reverseLinkedList(ListNodehead){
ListNodepre=nullptr;
ListNode*cur=head;
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode*dummyHead=new ListNode(0);
dummyHead->next=head;
};
递归
原地反转
打卡