Reverse part of a linked list 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-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL, m = 2 and n = 4, the function should return 1-&gt;4-&gt;3-&gt;2-&gt;5-&gt;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-&gt;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-&gt;next;
    }
    m_node = cur;
    before_m_node = prev;
    prev = cur, cur = cur-&gt;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-&gt;next;
        cur-&gt;next = prev;
        prev = cur, cur = temp;
    }

    after_n_node = cur-&gt;next;

    // if first node is not head of the list
    if (before_m_node != NULL)
    {
        cur-&gt;next = prev;
        m_node-&gt;next = after_n_node;
        before_m_node-&gt;next = cur;
        return head;
    }
    else
    {
        cur-&gt;next = prev;
        m_node-&gt;next = after_n_node;
        return cur;
    }
}
Redundancy in while loops

Your while loop has a condition that never gets used because there is an if statement inside the loop that actually ends the loop.  For example:


while (count != m)
{
    ++count;
    if (count == m)
    {
        break;
    }
    prev = cur, cur = cur-&gt;next;
}



You could simplify this by merging the increment into the loop condition.  Also, I don't using the comma operator to put two statements on one line.  So I would write your loop like this:

while (++count &lt; m)
{
    prev = cur;
    cur  = cur-&gt;next;
}


And your other loop would look like this:

while (++count &lt; n)
{
    struct ListNode* temp = cur-&gt;next;
    cur-&gt;next = prev;
    prev      = cur;
    cur       = temp;
}


Use typedef

I suggest using a typedef so you don't have to use struct so much.  For example:

typedef struct ListNode {
     int val;
     struct ListNode *next;
} ListNode;


And then use just ListNode instead of struct ListNode everywhere.