Skip to content

Commit 5aaed5c

Browse files
committed
feat: add LeetCode problem 92
Add iterative solution for Reverse Linked List II
1 parent e5dad3f commit 5aaed5c

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

leetcode/src/92.c

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
}

0 commit comments

Comments
 (0)