Cover image for Interview Classic 150 Problem P92 Reverse Linked List II

Interview Classic 150 Problem P92 Reverse Linked List II


Timeline

Timeline

2025-11-20

init

linked list

Problem:

In linked list problems, you generally cannot directly change the value of a node.

Use the head insertion method to reverse the linked list. Creating a dummy head node avoids some special cases. Also, at the end, you should not return head, but virt_head->next, because head may change due to swapping.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
struct ListNode {	int val;	ListNode *next;	ListNode()		: val(0)		, next(nullptr)	{	}	ListNode(int x)		: val(x)		, next(nullptr)	{	}	ListNode(int x, ListNode *next)		: val(x)		, next(next)	{	}};class Solution {    public:	ListNode *reverseBetween(ListNode *head, int left, int right)	{		int index = 0;		ListNode *virt_head = new ListNode;		virt_head->next = head;		ListNode *p = virt_head, *q;		while (p != nullptr) {			if (index + 1 == left) {				break;			}			index++;			p = p->next;		}		q = p;		while (q != nullptr) {			if (index == right) {				break;			}			index++;			q = q->next;		}		ListNode *tmp;		while (p->next != q) {			tmp = p->next;			p->next = tmp->next;			tmp->next = q->next;			q->next = tmp;		}		head = virt_head->next;		delete virt_head;		return head;	}};
Loading comments…