【ALGO】Leetcode 92. 反转链表 II

it2025-05-31  10

导航

题面解析AC代码

题面

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

解析

绘图方法求解链表题

AC代码

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { auto dummy = new ListNode(-1); dummy->next = head; // 点定位 auto a=dummy; for(int i=0; i<m-1; ++i) a=a->next; auto b=a->next, c=b->next; // 翻转 for(int i=0; i<n-m; ++i){ auto t = c->next; c->next = b; b=c, c=t; } a->next->next=c; a->next=b; return dummy->next; } };
最新回复(0)