法1:迭代写法
讲解看视频,非常清晰!!!灵茶山艾府
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
dummy = ListNode(next=head)
preLeftNode, leftNode = dummy, None # left的前续节点,left对应节点
for _ in range(left-1):
preLeftNode = preLeftNode.next
leftNode = preLeftNode.next
pre, cur = None, leftNode
for _ in range(right-left+1): # 共计right-left+1个结点需要反转
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
preLeftNode.next = pre
leftNode.next = cur
return dummy.next
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 {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode preStart = dummy, postEnd = dummy; // 记录要反转链表串的前驱, 后继结点
while (left > 1) {
preStart = preStart.next;
--left;
}
while (right >= 0) {
postEnd = postEnd.next;
--right;
}
// 翻转[preStart.next, postEnd)之间的结点
ListNode pre = null, cur = preStart.next;
while (cur != postEnd) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
preStart.next = pre; // 前段连接翻转后的起点
cur = pre;
while (cur.next != null) {
cur = cur.next;
}
cur.next = postEnd; // 翻转后的终点连接后段
return dummy.next;
}
}
博客围绕翻转部分链表展开,介绍了迭代写法来解决该问题,但未详细阐述具体内容。
1184

被折叠的 条评论
为什么被折叠?



