Mid From PDF Coding C# Coding Interview

Reverse a portion of a linked list (from position m to n)?

ListNode ReverseBetween(ListNode head, int m, int n) {
if (head == null || m == n) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;

// Move prev to one before m-th node

for (int i = 1; i < m; i++) prev = prev.next;
ListNode start = prev.next;
ListNode then = start.next;

// Reverse the sublist

for (int i = 0; i < n - m; i++) {

Follow on:

start.next = then.next;
then.next = prev.next;
prev.next = then;
then = start.next;
}
return dummy.next;
}

Explanation:

Use a dummy node to simplify edge cases. Reverse nodes between m and n by changing

pointers.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details