I'm learning data structures. I'm working on linked lists at the moment, and I'd like to have a strong grasp on them. Below is the last problem I solved. I'd like to know what you think of the solution and what can be done better.
The problem consists of reversing a linked list from position m
to position n
.
1 ≤ m ≤ n ≤ length of list
. If we have a list 1->2->3->4->5->NULL, m = 2 and n = 4
, the function should return 1->4->3->2->5->NULL
.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
if (head == NULL || head->next == NULL || m - n == 0)
{
return head;
}
struct ListNode* prev = NULL, *cur = head;
struct ListNode* before_m_node, *m_node, *after_n_node;
int count = 0;
// find m node, after loop cur points to m node, prev gets node befor or NULL if there is none
while (count != m)
{
++count;
if (count == m)
{
break;
}
prev = cur, cur = cur->next;
}
m_node = cur;
before_m_node = prev;
prev = cur, cur = cur->next;
// now we look for n node, cur is currently pointing to node after m, prev points to node before
// we will reverse links as we go and after loop cur will point to n node
while (count != n)
{
++count;
if (count == n)
{
break;
}
struct ListNode* temp = cur->next;
cur->next = prev;
prev = cur, cur = temp;
}
after_n_node = cur->next;
// if first node is not head of the list
if (before_m_node != NULL)
{
cur->next = prev;
m_node->next = after_n_node;
before_m_node->next = cur;
return head;
}
else
{
cur->next = prev;
m_node->next = after_n_node;
return cur;
}
}