92. 反转链表 II(翻转部分链表)

tech2025-06-11  4

题目: 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明: 1 ≤ m ≤ n ≤ 链表长度。

方法:双指针+穿针引线

函数代码:

class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if(!head) { return head; } ListNode *dummy=new ListNode(0); dummy->next=head; ListNode *pre=dummy; for(int i=0;i<m-1;i++) { pre=pre->next; } ListNode *p=pre->next; for(int i=m;i<n;i++) { ListNode *q=p->next; p->next=q->next; q->next=pre->next; pre->next=q; } return dummy->next; } };
最新回复(0)