File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ * 92. Reverse Linked List II
3+ * https://leetcode.com/problems/reverse-linked-list-ii/
4+ *
5+ * Given the head of a singly linked list and two integers left
6+ * and right where left <= right, reverse the nodes of the list
7+ * from position left to position right (1-indexed), and return
8+ * the reversed list.
9+ *
10+ * Approach: use a dummy node before head to simplify edge cases
11+ * (e.g. left == 1). Walk to the node just before position `left`,
12+ * then reverse the next (right - left + 1) nodes in place using
13+ * the same prev/curr pointer technique as a full list reversal,
14+ * finally reconnecting the reversed segment to the rest of the list.
15+ * Time: O(n), Space: O(1)
16+ */
17+
18+ struct ListNode {
19+ int val ;
20+ struct ListNode * next ;
21+ };
22+
23+ struct ListNode * reverseBetween (struct ListNode * head , int left , int right ) {
24+ struct ListNode dummy ;
25+ dummy .next = head ;
26+
27+ struct ListNode * before = & dummy ;
28+ for (int i = 1 ; i < left ; i ++ ) {
29+ before = before -> next ;
30+ }
31+
32+ struct ListNode * curr = before -> next ;
33+ struct ListNode * prev = NULL ;
34+
35+ for (int i = 0 ; i <= right - left ; i ++ ) {
36+ struct ListNode * next = curr -> next ;
37+ curr -> next = prev ;
38+ prev = curr ;
39+ curr = next ;
40+ }
41+
42+ before -> next -> next = curr ;
43+ before -> next = prev ;
44+
45+ return dummy .next ;
46+ }
You can’t perform that action at this time.
0 commit comments